using System.Drawing;
using System.Drawing.Imaging;
namespace Barcoded
{
internal class ImageHelpers
{
///
/// Resizes the given font to fit within the specified width.
///
/// String to be measured.
/// Available width.
/// Image DPI.
/// Font to be resized.
/// Limit maximum font size to the original font provided.
/// Font, size adjusted to fir width.
internal static Font GetSizedFontForWidth(int stringLength, int width, int dpi, Font font, bool limitSizeToFont = true)
{
return GetSizedFontForWidth(new string('\u0057', stringLength), width, dpi, font, limitSizeToFont);
}
///
/// Gets the font adjusted to the maximum size that will allow the given text to fit the given width.
///
/// Text that needs to fit
/// Available width
/// Image DPI
/// Font to be measured
/// Limit maximum font size returned to the font size provided
/// Font set to the maximum size that will fit
internal static Font GetSizedFontForWidth(string textToFit, int width, int dpi, Font font, bool limitSizeToFont = true)
{
Bitmap image = new Bitmap(width, 100);
image.SetResolution(dpi, dpi);
Graphics imageMeasure = Graphics.FromImage(image);
Font sizedFont = new Font(font.FontFamily, 1);
for (int fontSize = 1; fontSize <= 500; fontSize++)
{
Font tryFont = new Font(font.FontFamily, fontSize);
SizeF imageSize = imageMeasure.MeasureString(textToFit, tryFont);
if (imageSize.Width < width)
{
sizedFont = tryFont;
if (fontSize == (int)font.Size && limitSizeToFont) goto ExitFor;
}
else
{
goto ExitFor;
}
}
ExitFor:
image.Dispose();
imageMeasure.Dispose();
return sizedFont;
}
///
/// Returns the image width required for the given text drawn using the specified font.
///
/// String to be measured
/// Font to be used
/// Image DPI
/// Measured image size
internal static SizeF GetStringElementSize(string text, Font font, int dpi)
{
Bitmap bitmap = new Bitmap(1, 1);
bitmap.SetResolution(dpi, dpi);
Graphics graphics = Graphics.FromImage(bitmap);
SizeF size = graphics.MeasureString(text, font);
graphics.Dispose();
bitmap.Dispose();
return size;
}
///
/// Returns the image codec for the given codec name.
///
/// Codec name.
/// Will return PNG, if specified codec cannot be found.
/// Image codec.
internal static ImageCodecInfo FindCodecInfo(string codecName)
{
while (true)
{
codecName = codecName.ToUpper();
switch (codecName)
{
case "JPG":
codecName = "JPEG";
break;
case "TIF":
codecName = "TIFF";
break;
}
ImageCodecInfo[] encoders = ImageCodecInfo.GetImageEncoders();
foreach (ImageCodecInfo encoder in encoders)
{
if (encoder.FormatDescription.Equals(codecName))
{
return encoder;
}
}
codecName = "PNG";
}
}
}
}