Question

I'm saving both high resolution and compressed version of high resolution image in the database.

When the user requests a high resolution image, i need to display that else the compressed one. here is my code.

The issue is : when i set that image byte array into a stream and bitmap, file size has compressed 2.27MB to 339kB.

What i'm doing wrong here?

private void DisplayImageFromBytes(byte[] byteArray, int resizeWidth, bool isHiResImage)   {

if (isHiResImage)
{
    Stream stream = new MemoryStream(byteArray);
    System.Drawing.Image img = System.Drawing.Image.FromStream(stream);
    Bitmap bitmap = null;

    if (resizeWidth > 0 && img.Width > resizeWidth)
    {
        int newHeight = (int)((float)img.Height * ((float)resizeWidth / (float)img.Width));
        bitmap = new Bitmap(img, resizeWidth, newHeight);
    }
    else
    {
        bitmap = new Bitmap(img);
    }
    Response.ContentType = "image/Jpeg";
    bitmap.Save(Response.OutputStream, System.Drawing.Imaging.ImageFormat.Jpeg);
    stream.Dispose();
    img.Dispose();
    bitmap.Dispose();
}
else
{
    DisplayImageFromBytes(byteArray, resizeWidth);
}

}

Was it helpful?

Solution

You are using same image format to save it to stream for all the different format of images that came into you.

For now just replace

bitmap.Save(Response.OutputStream, System.Drawing.Imaging.ImageFormat.Jpeg);

with

bitmap.Save(Response.OutputStream, img.RawFormat);

RawFormat: will get the current file format of this Image.

N.B: You don't need to create a new bitmap that don't need any conversion. you can directly save it to stream from System.Drawing.Image img

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top