简体   繁体   中英

C# Image Resize from Stream

I'm trying to resize an image from stream. Getting the error

Value cannot be null.Parameter name: encoder

on the line

System.Drawing.Bitmap fullSizeBitmap = new System.Drawing.Bitmap(fullsizeImage, new System.Drawing.Size(width, image_height));

How do I add an encoder here? and I need it to be from the original image

   public static FileProperty UploadImage(IFormFile file, string folderPath, string fileName, FileNote note, int image_height)
    {

        FileProperty property = new FileProperty();

        if (file.Length > 0)
        {

            MemoryStream ms = new MemoryStream();
            file.CopyTo(ms);
            var fileBytes = ms.ToArray();

            MemoryStream inputMemoryStream = new MemoryStream(fileBytes);
            System.Drawing.Image fullsizeImage = System.Drawing.Image.FromStream(inputMemoryStream);

            int width = (image_height / fullsizeImage.Height) * fullsizeImage.Width;

            System.Drawing.Bitmap fullSizeBitmap = new System.Drawing.Bitmap(fullsizeImage, new System.Drawing.Size(width, image_height));

            using (var stream = new MemoryStream())
            {
                fullSizeBitmap.Save(stream, fullSizeBitmap.RawFormat);

                using (MemoryStream memoryStream = new MemoryStream(stream.ToArray()))
                {
                    UploadFromStreamAsync(memoryStream);
                }
            }

            property.FileName = fileName;
            property.FileExtention = Path.GetExtension(fileName);
            property.FileSize = file.Length;
            property.FileType = file.ContentType;
            property.FileNote = note.ToString();
        }

        return property;
    }

This resizes an image loaded from a file and save it to another file:

https://docs.microsoft.com/dotnet/api/system.drawing.image.save

using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;

var image = Image.FromFile(filename);
var bitmap = ResizeImage(image, widthNew, height.New);
bitmap.Save(filenameNew, image.RawFormat);

private Bitmap ResizeImage(Image image, int width, int height)
{
  var destRect = new Rectangle(0, 0, width, height);
  var destImage = new Bitmap(width, height);
  destImage.SetResolution(image.HorizontalResolution, image.VerticalResolution);
  using ( var graphics = Graphics.FromImage(destImage) )
  {
    graphics.CompositingMode = CompositingMode.SourceCopy;
    graphics.CompositingQuality = CompositingQuality.HighQuality;
    graphics.InterpolationMode = InterpolationMode.HighQualityBicubic;
    graphics.SmoothingMode = SmoothingMode.HighQuality;
    graphics.PixelOffsetMode = PixelOffsetMode.HighQuality;
    using ( var wrapMode = new ImageAttributes() )
    {
      wrapMode.SetWrapMode(WrapMode.TileFlipXY);
      graphics.DrawImage(image, destRect,
                         0, 0, image.Width, image.Height,
                         GraphicsUnit.Pixel, wrapMode);
    }
  }
  return destImage;
}

Just use file.OpenReadStream() to read and resize the file, then save the resized bitmap to the MemoryStream and upload.

And instead of using bitmap.RawFormat you can get the uploaded image format using a method as below:

if (file.Length > 0)
{
    using(var stream = file.OpenReadStream())
    {
        var image = Image.FromStream(stream);

        int width = (image_height / fullsizeImage.Height) * fullsizeImage.Width;        

        Bitmap fullSizeBitmap = new Bitmap(fullsizeImage, new Size(width, image_height));

        var imgFormat = GetImageFormat(file.FileName);

        using(var ms = new MemoryStream())
        {
            fullSizeBitmap.Save(ms, imgFormat);
            UploadFromStreamAsync(ms);
        }
    }
}

The method to get the image format by file extension:

public ImageFormat GetImageFormat(string fileName)
{
    var dotIndex = fileName.LastIndexOf('.');
    var ext = fileName.Substring(dotIndex, fileName.Length - dotIndex).ToLower();

    switch (ext)
    {
        case ".bmp": return ImageFormat.Bmp;
        case ".emf": return ImageFormat.Emf;
        case ".exif": return ImageFormat.Exif;
        case ".gif": return ImageFormat.Gif;
        case ".icon": return ImageFormat.Icon;
        case ".Jpg": return ImageFormat.Jpeg;
        case ".Jpeg": return ImageFormat.Jpeg;
        case ".png": return ImageFormat.Png;
        case ".tiff": return ImageFormat.Tiff;
        case ".Wmf": return ImageFormat.Wmf;
        default: throw new InvalidDataException("Format not supported");
    }
}

If you still need to get the uploaded image encoder info use the below method:

// ext: image extension
using System.Drawing.Imaging;

public static ImageCodecInfo GetEncoderInfo(string ext)
{
    return ImageCodecInfo.GetImageEncoders().SingleOrDefault(x => x.FilenameExtension.ToLower().Contains(ext));
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM