private bool MakePngBackgroundTransparent(string originalPath, string pathToProcessedImage)
{
try
{
using (var originalImage = PalasoImage.FromFileRobustly(originalPath))
{
//if it's a jpeg, we don't resize, we don't mess with transparency, nothing. These things
//are scary in .net. Just send the original back and wash our hands of it.
if (ImageUtils.AppearsToBeJpeg(originalImage))
{
return false;
}
//impose a maximum size because in BL-2871 "Opposites" had about 6k x 6k and we got an ArgumentException
//from the new BitMap()
var destinationWidth = Math.Min(1000, originalImage.Image.Width);
var destinationHeight = (int)((float)originalImage.Image.Height*((float)destinationWidth/ (float)originalImage.Image.Width));
using (var processedBitmap = new Bitmap(destinationWidth, destinationHeight))
{
using (var g = Graphics.FromImage(processedBitmap))
{
var destRect = new Rectangle(0, 0, destinationWidth, destinationHeight);
lock (_convertWhiteToTransparent)
{
g.DrawImage(originalImage.Image, destRect, 0, 0, originalImage.Image.Width, originalImage.Image.Height,
GraphicsUnit.Pixel, _convertWhiteToTransparent);
}
}
//Hatton July 2012:
//Once or twice I saw a GDI+ error on the Save below, when the app 1st launched.
//I verified that if there is an IO error, that's what you get (a GDI+ error).
//I looked once, and the %temp%/Bloom directory wasn't there, so that's what I think caused the error.
//It's not clear why the temp/bloom directory isn't there... possibly it was there a moment ago
//but then some startup thread cleared and deleted it? (we are now running on a thread responding to the http request)
Exception error = null;
for (var i = 0; i < 3; i++) //try three times
{
try
{
error = null;
SIL.IO.RobustIO.SaveImage(processedBitmap, pathToProcessedImage, originalImage.Image.RawFormat);
break;
}
catch (Exception e)
{
Logger.WriteEvent("***Error in RuntimeImageProcessor while trying to write image.");
Logger.WriteEvent(e.Message);
error = e;
//in setting the sleep time, keep in mind that this may be one of 20 images
//so if the problem happens to all of them, then you're looking 20*retries*sleep-time,
//which will look like hung program.
//Meanwhile, this transparency thing is actually just a nice-to-have. If we give
//up, it's ok.
Thread.Sleep(100); //wait a 1/5 second before trying again
}
}
if (error != null)
{
throw error;//will be caught below
}
}
}
return true;
}
//we want to gracefully degrade if this fails (as it did once, see comment in bl-2871)
catch (TagLib.CorruptFileException e)
{
NonFatalProblem.Report(ModalIf.Beta, PassiveIf.All, "Problem with image metadata", originalPath, e);
return false;
}
catch (Exception e)
{
//while beta might make sense, this is actually
//a common failure at the moment, with the license.png
//so I'm setting to alpha.
NonFatalProblem.Report(ModalIf.Alpha, PassiveIf.All,"Problem making image transparent.", originalPath,e);
return false;
}
}