[英]When converting an uploaded jpeg to byte array it finishes as png?
我正在上载jpeg图像,并将其作为字节数组存储在数据库中。 但是,当我检索图像并选择“另存为”时,图像现在是PNG,文件大小要大60-70%。 这是进行转换的功能。 有人可以建议为什么会这样吗?
private byte[] ResizeImage(UploadedFile file, int maxWidth, int maxHeight)
{
int canvasWidth = maxWidth;
int canvasHeight = maxHeight;
using (Bitmap originalImage = new Bitmap(file.InputStream))
{
int originalWidth = originalImage.Width;
int originalHeight = originalImage.Height;
Bitmap thumbnail = new Bitmap(canvasWidth, canvasHeight); // create thumbnail canvas
using (Graphics g = Graphics.FromImage((System.Drawing.Image)thumbnail))
{
g.SmoothingMode = SmoothingMode.Default;
g.InterpolationMode = InterpolationMode.Default;
g.PixelOffsetMode = PixelOffsetMode.Default;
//Get the ratio of original image
double ratioX = (double)canvasWidth / (double)originalWidth;
double ratioY = (double)canvasHeight / (double)originalHeight;
double ratio = ratioX < ratioY ? ratioX : ratioY; // use which ever multiplier is smaller
// Calculate new height and width
int newHeight = Convert.ToInt32(originalHeight * ratio);
int newWidth = Convert.ToInt32(originalWidth * ratio);
// Calculate the X,Y position of the upper-left corner
// (one of these will always be zero)
int posX = Convert.ToInt32((canvasWidth - (originalWidth * ratio)) / 2);
int posY = Convert.ToInt32((canvasHeight - (originalHeight * ratio)) / 2);
//g.Clear(Color.White); // Add white padding
g.DrawImage(originalImage, posX, posY, newWidth, newHeight);
}
/* Display uploaded image preview */
ImageConverter converter = new ImageConverter();
byte[] imageData = (byte[])converter.ConvertTo(thumbnail, typeof(byte[])); // Convert thumbnail into byte array and set new binary image
return imageData;
}
}
我不确定ImageConverter
是否支持其他格式,因此请尝试
byte[] imageData;
using (MemoryStream stream = new MemoryStream())
{
thumbnail.Save(stream, ImageFormat.Jpeg);
imageData = stream.ToArray();
}
return byteArray;
如果你想要更多的控制(例如指定压缩级别),检查这出。
似乎缺少ImageConverter上的文档,但是可以猜测的是,除非另外指定,否则它默认会将其转换为PNG(假设它甚至支持其他格式)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.