我需要允许我的用户上传图片,为此我需要显示缩略图。我需要确保缩略图不大于 8000 字节。
我正在使用nQuant(产生高质量 256 色 8 位 PNG 图像的颜色量化器)来量化图像并将其缩小为 8 位图像,而不是 32 位,从而大大减小了文件大小。
我想知道的是始终低于 8000 字节的图像的最大尺寸是多少?
目前我使用 96 x 96 作为我的最大尺寸并且我没有超过 8000 字节的限制,但我不知道这是否是因为我正在测试转换器的源图像(我的 HD 上的 194 张随机图片),或者因为其他原因。
当我现在在想它时,我想知道是否给予了
96 * 96 = 9216 (bytes)
假设我的推理在数学上是错误的,这是正确的吗?
我是否应该考虑将最大尺寸减小到
89 * 89 = 7921 (bytes)
作为参考,这是转换器:
var fileSystemInfos = new DirectoryInfo(sourcePath).GetFiles();
var i = 0;
var total = fileSystemInfos.Count();
foreach (var file in fileSystemInfos)
{
using (var inputStream = new FileStream(file.FullName, FileMode.Open))
using (var memoryStream = new MemoryStream())
{
using (var sourceBitmap = new Bitmap(inputStream))
{
var img = ResizeImage(sourceBitmap, 96, 96);
QuantizeImage(img, memoryStream);
var outputName = file.Name.Replace("JPG", "png");
using (var outputStream = new FileStream(Path.Combine(outputPath, outputName), FileMode.Create))
{
memoryStream.Seek(0, SeekOrigin.Begin);
memoryStream.CopyTo(outputStream);
}
}
}
Console.WriteLine(++i + " of " + total);
}
private static void QuantizeImage(Bitmap bmp, MemoryStream outputFile)
{
var quantizer = new WuQuantizer();
using (var quantized = quantizer.QuantizeImage(bmp))
{
try
{
quantized.Save(outputFile, ImageFormat.Png);
}
catch (System.Exception ex)
{
// deal with error
}
}
}
public static Bitmap ResizeImage(Bitmap image, int maxWidth, int maxHeight)
{
int originalWidth = image.Width;
int originalHeight = image.Height;
// To preserve the aspect ratio
float ratioX = (float)maxWidth / (float)originalWidth;
float ratioY = (float)maxHeight / (float)originalHeight;
float ratio = Math.Min(ratioX, ratioY);
// New width and height based on aspect ratio
int newWidth = (int)(originalWidth * ratio);
int newHeight = (int)(originalHeight * ratio);
// Convert other formats (including CMYK) to RGB.
//Bitmap newImage = new Bitmap(newWidth, newHeight, PixelFormat.Format24bppRgb);
Bitmap newImage = new Bitmap(newWidth, newHeight, PixelFormat.Format32bppArgb);
// Draws the image in the specified size with quality mode set to HighQuality
using (Graphics graphics = Graphics.FromImage(newImage))
{
graphics.CompositingQuality = CompositingQuality.HighQuality;
graphics.InterpolationMode = InterpolationMode.HighQualityBicubic;
graphics.SmoothingMode = SmoothingMode.HighQuality;
graphics.DrawImage(image, 0, 0, newWidth, newHeight);
}
return newImage;
}