-1

I'm resizing an image, what could be wrong with my code?

var newSize = ResizeImageFile(ConvertToBytes(myFile), 2048);
using (MemoryStream ms = new MemoryStream(newSize, 0, newSize.Length))
{
  ms.Write(newSize, 0, newSize.Length);
  using (Image image = Image.FromStream(ms, true))
  {
    image.Save(targetLocation, ImageFormat.Jpeg);
  }
}

I have used this function to resize my image

public static byte[] ResizeImageFile(byte[] imageFile, int targetSize) // Set targetSize to 1024
        {
            using (Image oldImage = Image.FromStream(new MemoryStream(imageFile)))
            {
                Size newSize = CalculateDimensions(oldImage.Size, targetSize);
                using (Bitmap newImage = new Bitmap(newSize.Width, newSize.Height, PixelFormat.Format24bppRgb))
                {
                    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();
                    }
                }
            }
        }

I have been looking for answers for a long time, please help me. Thank you

huy Le
  • 1
  • You probably simply don't have permissions to write at `targetLocation`. At least, I guess the exception occurs at `image.Save()`? Please read [ask] and show what you have tried. – CodeCaster Apr 16 '19 at 10:55

1 Answers1

-1

Since the both CalculateDimensions and ConvertToBytes methods are not shown, I tried to assume that the above methods are something like as follows:

// Calculate the Size at which the image width and height is lower than the specified value
// (Keep the aspect ratio)
private static Size CalculateDimensions(Size size, int targetSize)
{
    double rate = Math.Max(size.Width * 1.0 / targetSize, size.Height * 1.0 / targetSize);
    int w = (int)Math.Floor(size.Width / rate);
    int h = (int)Math.Floor(size.Height / rate);
    return new Size(w, h);
}

//Convert image file to byte array
private static byte[] ConvertToBytes(string fileName)
{
    var result = File.ReadAllBytes(fileName);
    return result;
}

If your code does not work well, then some problems must be in the above methods.

Nazonokaijin
  • 121
  • 10
  • Please read [answer]. Don't guess that the problem is in code which is not shown and then tell the OP to fix that. – CodeCaster Apr 16 '19 at 10:55