将上传的jpeg转换为字节数组时,它是否以png结尾?

时间:2013-01-23 11:42:58

标签: c# system.drawing

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

2 个答案:

答案 0 :(得分:4)

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

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

如果您想要更多控制(例如指定压缩级别),请检查this输出。

答案 1 :(得分:0)

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