6

I am unable to save the jpg image using SixLabors.ImageSharp version - 1.0.0-beta0007 in c#, It throws error. Is there any solution to fix the issue beside GIF,PNG,JPEG,BMP format images.

Throws Exception:

Image cannot be loaded. Available decoders:

  • GIF : GifDecoder
  • PNG : PngDecoder
  • JPEG : JpegDecoder
  • BMP : BmpDecoder

Code:

    public string ResizeImage(byte[] imageBytes, int height, int width)
    {
        byte[] image = new byte[] { };

        using (MemoryStream inStream = new MemoryStream(imageBytes))
        {
            using (MemoryStream outStream = new MemoryStream())
            {
                using (Image imageSharp = Image.Load(inStream))
                {
                    imageSharp.Mutate(x => x.Resize(width, height));
                    imageSharp.SaveAsJpeg(outStream);
                    imageSharp.Dispose();
                }

                image = outStream.ToArray();
                outStream.Flush();
                inStream.Flush();
            }
        }
        return Convert.ToBase64String(image);
    }
Jay Raj Mishra
  • 110
  • 2
  • 9

2 Answers2

8

Make sure the stream position is zero or try to copy the stream to new stream then set the position to zero because sometimes azure blob service close the returned stream

using (MemoryStream stream = new MemoryStream())
using (var ms = new MemoryStream())                                    
await largeBlob.DownloadToAsync(ms);
      ms.Position = 0;
      ms.CopyTo(stream);
      stream.Position = 0;
     var image = Image.Load(stream, out IImageFormat format)
Amer Jamaeen
  • 677
  • 8
  • 16
1

This will be because of a strange thing the AWS does with file uploads you will find the byte[] isn't actually a valid image file (testable by saving the raw byte array out).

This answer from another question should help you reconfigure AWS to allow your code to work.

https://stackoverflow.com/a/56695747/234855

tocsoft
  • 1,709
  • 16
  • 22
  • I basically want to find the issue and fixed in C# not on AWS, We convert the base url to base64 to hold on memory stream for resizing and the images come from feed etl. – Jay Raj Mishra Jan 17 '20 at 05:09
  • Is there is any Image Library for converting the images to any format. – Jay Raj Mishra Jan 22 '20 at 06:53
  • The issue is with AWS configuration, not with the library, nor anything in C#. – James South Jan 29 '20 at 08:10
  • @James South AWS configuration is fine, from the plugin code it is throwing exception. – Jay Raj Mishra Jan 30 '20 at 06:41
  • Having now seen this https://github.com/SixLabors/ImageSharp/issues/1101 I can see that the issue is clearly not with the library. You're trying to load images that are of an unsupported format which you do not mention above!!! – James South Jan 31 '20 at 04:40