private string FindOrGenerateThumbnail(string expectedPathOfThumbnailImage)
{
var localPath = AdjustPossibleLocalHostPathToFilePath(expectedPathOfThumbnailImage);
var svgpath = Path.ChangeExtension(localPath, "svg");
if (File.Exists(svgpath))
{
return svgpath;
}
var pngpath = Path.ChangeExtension(localPath, "png");
if (File.Exists(pngpath))
{
return pngpath;
}
// We don't have an image; try to make one.
var templatesDirectoryInTemplateBook = Path.GetDirectoryName(expectedPathOfThumbnailImage);
var bookPath = Path.GetDirectoryName(templatesDirectoryInTemplateBook);
var templateBook = _bookFactory(new BookInfo(bookPath,false), _storageFactory(bookPath));
//note: the caption is used here as a key to find the template page.
var caption = Path.GetFileNameWithoutExtension(expectedPathOfThumbnailImage).Trim();
var isLandscape = caption.EndsWith("-landscape"); // matches string in page-chooser.ts
if (isLandscape)
caption = caption.Substring(0, caption.Length - "-landscape".Length);
// The Replace of & with + corresponds to a replacement made in page-chooser.ts method loadPagesFromCollection.
IPage templatePage = templateBook.GetPages().FirstOrDefault(page => page.Caption.Replace("&", "+") == caption);
if (templatePage == null)
templatePage = templateBook.GetPages().FirstOrDefault(); // may get something useful?? or throw??
Image thumbnail = _thumbNailer.GetThumbnailForPage(templateBook, templatePage, isLandscape);
// lock to avoid BL-3781 where we got a "Object is currently in use elsewhere" while doing the Clone() below.
// Note: it would appear that the clone isn't even needed, since it was added in the past to overcome this
// same contention problem (but, in hindsight, only partially, see?). But for some reason if we just lock the image
// until it is saved, we get all gray rectangles. So for now, we just quickly do the clone and unlock.
var resultPath = "";
Bitmap clone;
// Review: the coarse lock(SyncObj) in EnhancedImageServer.ProcessRequest() may have removed the need for this finer grained lock.
lock (thumbnail)
{
clone = new Bitmap((Image)thumbnail.Clone());
}
using (clone)
{
try
{
//if the directory doesn't exist in the template's directory, make it (i.e. "templates/").
Directory.CreateDirectory(templatesDirectoryInTemplateBook);
//save this thumbnail so that we don't have to generate it next time
clone.Save(pngpath);
resultPath = pngpath;
}
catch (Exception)
{
using (var file = new TempFile())
{
clone.Save(file.Path);
resultPath = file.Path;
}
}
}
return resultPath;
}