1

I am developing an ASP.NET web application in which I am allowing my users to upload either jpeg,gif,bmp or png images.If the uploaded image size are greater then 1 mb . then I want to resize image into 15-16 Kb with Demission 230*300 without losing Image Quality.after resize image should be view good in 230*300 Demission ,please help me anyone .

protected void btnSubmit_Click(object sender, EventArgs e)
{
    if (IsValid)
    {
        Bitmap image = ResizeImage(fileImage.PostedFile.InputStream, 400, 800);
        image.Save(Server.MapPath("~/Photos/") + Guid.NewGuid().ToString() + ".jpg", ImageFormat.Jpeg);

        image.Dispose();
    }
}

private Bitmap ResizeImage(Stream streamImage, int maxWidth, int maxHeight)
{
    Bitmap originalImage = new Bitmap(streamImage);
    int newWidth = originalImage.Width;
    int newHeight = originalImage.Height;
    double aspectRatio = (double)originalImage.Width / (double)originalImage.Height;

    if (aspectRatio <= 1 && originalImage.Width > maxWidth)
    {
        newWidth = maxWidth;
        newHeight = (int)Math.Round(newWidth / aspectRatio);
    }
    else if (aspectRatio > 1 && originalImage.Height > maxHeight)
    {
        newHeight = maxHeight;
        newWidth = (int)Math.Round(newHeight * aspectRatio);
    }

    Bitmap newImage = new Bitmap(originalImage, newWidth, newHeight);

    Graphics g = Graphics.FromImage(newImage);
    g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBilinear;
    g.DrawImage(originalImage, 0, 0, newImage.Width, newImage.Height);

    originalImage.Dispose();

    return newImage;     
}
Soner Gönül
  • 97,193
  • 102
  • 206
  • 364

1 Answers1

0

this code was used in my project please ref this below code.

private Image RezizeI(Image img, int maxW, int maxH)
{
if(img.Height < maxH && img.Width < maxW) return img;
using (img)
{
    Double xRatio = (double)img.Width / maxW;
    Double yRatio = (double)img.Height / maxH;
    Double ratio = Math.Max(xRatio, yRatio);
    int nnx = (int)Math.Floor(img.Width / ratio);
    int nny = (int)Math.Floor(img.Height / ratio);
    Bitmap cpy = new Bitmap(nnx, nny, PixelFormat.Format32bppArgb);
    using (Graphics gr = Graphics.FromImage(cpy))
    {
        gr.Clear(Color.Transparent);

        // This is said to give best quality when resizing images
        gr.InterpolationMode = InterpolationMode.HighQualityBicubic;

        gr.DrawImage(img,
            new Rectangle(0, 0, nnx, nny),
            new Rectangle(0, 0, img.Width, img.Height),
            GraphicsUnit.Pixel);
    }
    return cpy;
 }
 }
 private MemoryStream BytearrayToStream(byte[] arr)
{
  return new MemoryStream(arr, 0, arr.Length);
}

 private void HandleImageUpload(byte[] binaryImage)
{
Image img = RezizeI(Image.FromStream(BytearrayToStream(binaryImage)), 103, 32);
img.Save("Test.png", System.Drawing.Imaging.ImageFormat.Gif);
}
Parth Akbari
  • 641
  • 7
  • 24