【发布时间】:2013-10-16 21:18:31
【问题描述】:
我需要允许我的用户上传图片,我需要为此显示缩略图。我需要确保缩略图不大于 8000 字节。
我正在使用nQuant(产生高质量 256 色 8 位 PNG 图像的颜色量化器)来量化图像并将其缩小为 8 位图像,而不是 32 位,从而大大减小了文件大小。
我想知道的是,始终小于 8000 字节的图像的最大尺寸是多少?
目前我使用 96 x 96 作为我的最大尺寸并且我没有超过 8000 字节的限制,但我不知道这是否是因为我正在测试转换器的源图像(194 张随机图片在我的 HD 上),或由于其他原因。
我现在正在考虑它,我想知道是否考虑到这一点
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;
}
【问题讨论】: