ASP.NET Image uploading with Resizing

前端 未结 14 1843
广开言路
广开言路 2020-11-30 01:27

I have an aspx page which will upload images to server harddisk from client pc

But now i need to change my program in such a way that it would allow me to resize the

14条回答
  •  北海茫月
    2020-11-30 01:42

    You can use this, it does a dandy job for me. But it does not handle low res images well for me. Thankfully I down use to many of them. Just sent it the image byte[] and the expected output and you'll be good to go.

    public static byte[] ResizeImageFile(byte[] imageFile, int targetSize) 
    { 
        using (System.Drawing.Image oldImage = System.Drawing.Image.FromStream(new MemoryStream(imageFile))) 
        { 
            Size newSize = CalculateDimensions(oldImage.Size, targetSize); 
    
            using (Bitmap newImage = new Bitmap(newSize.Width, newSize.Height, PixelFormat.Format32bppRgb)) 
            { 
                newImage.SetResolution(oldImage.HorizontalResolution, oldImage.VerticalResolution); 
                using (Graphics canvas = Graphics.FromImage(newImage)) 
                { 
                    canvas.SmoothingMode = SmoothingMode.AntiAlias; 
                    canvas.InterpolationMode = InterpolationMode.HighQualityBicubic; 
                    canvas.PixelOffsetMode = PixelOffsetMode.HighQuality; 
                    canvas.DrawImage(oldImage, new Rectangle(new Point(0, 0), newSize)); 
                    MemoryStream m = new MemoryStream(); 
                    newImage.Save(m, ImageFormat.Jpeg); 
                    return m.GetBuffer(); 
                } 
            } 
    
        } 
    } 
    
    private static Size CalculateDimensions(Size oldSize, int targetSize) 
    { 
        Size newSize = new Size(); 
        if (oldSize.Width > oldSize.Height) 
        { 
            newSize.Width = targetSize; 
            newSize.Height = (int)(oldSize.Height * (float)targetSize / (float)oldSize.Width); 
        } 
        else 
        { 
            newSize.Width = (int)(oldSize.Width * (float)targetSize / (float)oldSize.Height); 
            newSize.Height = targetSize; 
        } 
        return newSize; 
    } 
    

提交回复
热议问题