Home > Net >  Problem with converting string into image
Problem with converting string into image

Time:08-09

I need to download in image format (let's say JPEG) from the webapi response. Content string looks something like this:

����\0\u0010JFIF\0\u0001\u0001\0\0�\0�\0\0��\0�Exif\0\0MM\0*\0\0\0\b\0\u0006\u0001\u0012\0\u0003\0\0\0\u0001\0\u0001\0\0\u0001\u001a\0\u0005\0\0\0\u0001\0\0\0V\u0001\u001b\0\u0005\0\0\0\u0001\0\0\0^\u0001(\0\u0003\0\0\0\u0001\0\u0002\0\0�i\0\u0004\0\0\0\u0...

I see 2 problems that I don't understand how to solve

  1. encoding the string to the format that is required for conversion to .JPEG file
  2. saving this data in image format

I tried to use the encryption method, and standard encodings like UTF 7, 8, 32, Ascii, Unicode, and save it to a file via streams.But output image still not correct.

CodePudding user response:

As per DiplomacyNotWar's comment, you need to download as a Byte Array. Once you have the Byte Array you can create a file, I use NewtonSoft JsonConvert but there are many ways to achieve this.

Something like this should work:

byte[] byteArray = JsonConvert.DeserializeObject<byte[]>(response.MyImage);

using (FileStream fs = File.Create("YourFilePath"))
{
     fs.Write(byteArray, 0, byteArray.Length);
}

CodePudding user response:

Lately I'm busy building a service which retrieves files from an API as a byte[] with a list of properties, one of them containing the file extension. The service stores these files in a Blob Storage with the right file extension. To create a file (image in your case) from a byte[] you can use the following code.

Using a HttpClient you can do the following:

var response = client.GetAsync(endpoint);
var downloadedImage = await response.Result.Content.ReadAsByteArrayAsync();

And to create a file:

File.WriteAllBytes("somePath/image.jpeg", downloadedImage);

The file can be found in the given path. If you don't specify a specific path the file will be found in the somewhere inside the 'bin' folder of your project after a completed run. Remember to add the right file extension in your first argument (the one with the path) or else a file will be created with no extension. Pass in as a second argument the byte[]. Works fine here.

This should work 100% if the received content from the API isn't encoded. If the content is encoded you might wanna decode it and then store the value as a byte[] before you can use my code.

  • Related