将上传的 jpeg 转换为字节数组时,它以 png 完成

本文关键字:数组 它以 完成 png 字节数 字节 jpeg 转换 | 更新日期: 2023-09-27 17:55:15

我正在上传一个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;
    }
}

将上传的 jpeg 转换为字节数组时,它以 png 完成

我不确定ImageConverter是否支持其他格式,所以请尝试

byte[] imageData;
using (MemoryStream stream = new MemoryStream())
{
    thumbnail.Save(stream, ImageFormat.Jpeg);
    imageData = stream.ToArray();
}
return byteArray;

如果您想要更多控制(例如指定压缩级别),请查看此内容。

ImageConverter 上的文档似乎有点缺乏,但猜测是它默认将其转换为 PNG,除非另有说明(假设它甚至支持其他格式)。