Search code examples
c#system.drawing

When converting an uploaded jpeg to byte array it finishes as png?


I am uploading a jpeg image and storing it in a database as a byte array. However when i retrieve the image and select 'save as' the image is now a PNG and the file size is 60-70% larger. Here is the function which does the converting. Can anybody suggest why this is happening?

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;
    }
}

Solution

  • I'm not sure whether ImageConverter supports other formats, so try

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

    If you want more control (e.g. specify the compression level), check this out.