0

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

2 回答 2

4

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

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

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

于 2013-01-23T11:58:40.053 回答
0

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

于 2013-01-23T11:53:26.033 回答