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.
CodePudding user response:
I still use this code
byte[] image2 = response.Shipments[0].ShippingLabel.ToArray();
MemoryStream memoryStream = new MemoryStream(image2);
BinaryReader rd = new BinaryReader(memoryStream);
string filename = "C:/Users/CS/Documents/FedexLabel.png";
byte[] buffer = new byte[1024];
FileStream outFile = new FileStream(filename, FileMode.Create);
int bytesRead;
while ((bytesRead = memoryStream.Read(buffer, 0, buffer.Length)) != 0)
outFile.Write(buffer, 0, bytesRead);
outFile.Close();
CodePudding user response:
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");
//......
}