0

How do I convert a byte[] that holds a png image into a file to be saved on the filesystem?

   using MemoryStream memoryStream = new 
   MemoryStream(response.Shipments[0].ShippingLabel);
   memoryStream.Position = 0;
   System.Drawing.Image image = System.Drawing.Image.FromStream(memoryStream);
   image.Save(@"C:\\Users\CS\Documents\FedexLabel.png", ImageFormat.Png);

The code above keeps throwing this error:

    System.AggregateException
    HResult=0x80131500
    Message=One or more errors occurred. (Parameter is not valid.)
    Source=System.Private.CoreLib
    StackTrace:
    at System.Threading.Tasks.Task.Wait(Int32 millisecondsTimeout, CancellationToken 
    cancellationToken)
    at System.Threading.Tasks.Task.Wait()
    at ConsoleApp3.Program.Main(String[] args) in 

    This exception was originally thrown at this call stack:
    [External Code]
    Marketplace.FedexServices.FedexServicesTest.TestFedexCreateShipmentService() in 
    FedexServicesTest.cs

    Inner Exception 1:
    ArgumentException: Parameter is not valid.
  • 1
    You have a double backslash in the path. I'm not so sure that is legal. – Bent Tranberg Dec 23 '21 at 04:09
  • @bent-tranberg `.Save` doesn't throw `ArgumentException`, but `System.Drawing.Image.FromStream(...)` does, so it's likely that the image data is not valid in this case. – jhmckimm Dec 23 '21 at 04:17
  • 1
    FYI `File.WriteAllBytes` exists. I would probably use that to write it. If you don't 100% trust the source of those bytes, it might still be a good idea to check that it is a valid image before writing it though. – ProgrammingLlama Dec 23 '21 at 04:33
  • The bytes are coming directly from the other server. Should I use Convert.ToBase64()? What would File.WriteAllBytes output? –  Dec 23 '21 at 04:46
  • Have you checked this link? https://stackoverflow.com/questions/9173904/byte-array-to-image-conversion – Senthi Sri Dec 23 '21 at 05:42
  • Wouldn't `File.WriteAllBytes` output the bytes? Your question title indicates you have the bytes already... please edit if that isn't correct. – ProgrammingLlama Dec 23 '21 at 09:57

1 Answers1

0

I write a demo to convert byte[] image to file and save.

Manage Nuget Packages: System.Drawing.Common ;

public IActionResult Index(byte[] fileBytes)
        {
            
            //Convert byte type pictures into files to save
            var im = new System.IO.MemoryStream(fileBytes);
            var img = Image.FromStream(im);

            //save the file
            img.Save(@"C:\Users\CS\Documents\FedexLabel.png");
    

            //......

        }
Xinran Shen
  • 8,416
  • 2
  • 3
  • 12