converting base64 to image and showing in gridview - c#

i'm working on a website that takes its data from a web service. Our Android developer gave me a Base64 string like this.
iVBORw0KGgoAAAANSUhEUgAAAKAAAAB4CAYAAAB1ovlvAAAABHNCSVQICAgIf. . . . . . . . . .
I'm saving this string to my database. I would like to know how I can convert this to an image.

Here is the solution for you
public Image Base64ToImage(string base64String)
{
// Convert Base64 String to byte[]
byte[] imageBytes = Convert.FromBase64String(base64String);
MemoryStream ms = new MemoryStream(imageBytes, 0,imageBytes.Length);
// Convert byte[] to Image
ms.Write(imageBytes, 0, imageBytes.Length);
Image image = Image.FromStream(ms, true);
return image;
}

If you're showing it in a web page (You added asp.net as one of your tags so I'm assuming this is for the web) you can cheat and do this:
<img src="data:image/png;base64,<%=base64String%>"/>
This assumes that the image is a png, otherwise change it to image/jpg or whatever.
The downside is this stops the image being cached. So in practice the solution by #Sachin is more practical. This way is just neat if you want to avoid saving the files for whatever reason (or just want a 'I need it to work now' solution)

Related

In Unity trying to convert a Base64String to a png

I'm getting a Base64String from an API (Stable Horde)
I tried using
filePath = some path + image.png
File.WriteAllBytes(filePath, Convert.FromBase64String(myImageData.generations[0].img));
This does create an image on the hard drive but its not really a png image so when I try to read all bytes
back into an image in the scene there is a problem. Doesn't work. I figured out that this is because it was not encoded correctly into a real png in the first place.
I'm trying to translate this python code (into Unity C#) that does create an actual png:
b64img = results[iter]["img"]
base64_bytes = b64img.encode('utf-8')
img_bytes = base64.b64decode(base64_bytes)
img = Image.open(BytesIO(img_bytes))
if len(results) > 1:
final_filename = f"{iter}_{filename}"
img.save(final_filename)
I've been trying solutions searching online for about 16 hours with no luck. Can't believe how poorly documented and hard to do this is?
Can anyone help? What's the correct way to take a Base64String and convert it to a png in Unity C#.
Thanks!
Try this:
string base64String = "(your base64 string)";
byte[] data = System.Convert.FromBase64String(base64String);
Texture2D texture = new Texture2D(0, 0);
ImageConversion.LoadImage(texture, data);

flip image in before send it to API as Base64 Xamarin forms

I pick an image from the device and it's mirrored that's normal but I want to flip it horizontally before send it to API as to preview it after that normal not mirrored and do this on base64 string image.
You have not posted all the information however.
In Xamarin Forms Platform you can use FFImageLoading plugin which supports the transformation you are looking for. It support:
FlipTransformation
RotateTransformation
Follow the link to find their implementation here:
https://github.com/luberda-molinet/FFImageLoading/blob/master/samples/ImageLoading.Forms.Sample/Shared/Pages/Transformations/FlipTransformationPage.xaml
Your question did not explain clearly what you want to do.You can update it with more detail you want to conver what type to what type First.Whatever, I show a possible answer.
image path to base64 string:
// provide read access to the file
FileStream fs = new FileStream(media.Path, FileMode.Open,FileAccess.Read);
// Create a byte array of file stream length
byte[] ImageData = new byte[fs.Length];
//Read block of bytes from stream into the byte array
fs.Read(ImageData,0,System.Convert.ToInt32(fs.Length));
//Close the File Stream
fs.Close();
string _base64String = Convert.ToBase64String (ImageData);
base64 string to byte[]:
byte[] data = Convert.FromBase64String (FileRespone);
I used to flip the image as bitmap not Base64
in Android
https://acomputerengineer.wordpress.com/2016/06/07/flip-imagebitmap-horizontally-and-vertically-in-android/
in IOS:
How to flip UIImage horizontally?
UIImage sourceImage = uiImage;//[UIImage imageNamed: #"whatever.png"];
UIImage flippedImage = sourceImage.GetImageFlippedForRightToLeftLayoutDirection();
//[UIImage imageWithCGImage: sourceImage.CGImage scale: sourceImage.scale orientation: UIImageOrientationUpMirrored];

Saving a image that was converted into byte[] without System.Drawing?

Yes you can just use:
// A byte array that contains a .jpeg data.
System.IO.Stream BitmapStream = System.IO.MemoryStream(byteBuffer);
System.Drawing.Bitmap MyImage = System.Drawing.Bitmap.FromStream(BitmapStream);
MyImage.Save("C:\Folder\Folder\image.jpeg", System.Drawing.Imaging.ImageFormat.Jpeg);
But how could you do this without System.Drawing?
I would like to write my own code to create the image.
If you have the image in bytes you don't need to use drawing to make an image, just save it as a binary file.
System.IO.File.WriteAllBytes("C:\Folder\Folder\image.png", byteBuffer);

Validating a base64 encoded image .NET core

I'm building an API that among other things allows users to change their photo. This photo is sent in as a base64 string and I want to be able to validate that it's an actual .jpeg or .png format.
Since System.Drawing is missing in .NET core i'm not sure how to go about doing this. Before i could have simply used something like
public Image Base64ToImage(string base64String)
{
// Convert base 64 string to byte[]
byte[] imageBytes = Convert.FromBase64String(base64String);
// Convert byte[] to Image
using (var ms = new MemoryStream(imageBytes, 0, imageBytes.Length))
{
Image image = Image.FromStream(ms, true);
return image;
}
}
and then gone from there to check what i needed about the Image.
Any help would be appreciated
When you don't have System.Drawing I would look at the actual bytes instead to see if they match the JPEG or PNG file standard.
For a PNG file the first eight bytes always contains the following decimal values: 137 80 78 71 13 10 26 10 (Source)
A JPEG file is more complex but it can be done as well. The first two bytes, at least, seems to always be 0xFF 0xD8 (Source). Read a bit more about the file structure to get better comparison values.
Based on this you can do a simple comparison on the bytes in your imageBytes array.

Creating a PNG source from data in memory

Situation:
I am reading a PNG file, encoded with base64 from a server (JSON Format). Works fine.
There is NO direct URL to the ressource (just like: http:... / image.png or simuliar), so i read the data (which is part of a JSON object), decode in from the base64 Encoding and store it in a byte[].
Want i want: Display this PNG on a certain page ( like:
ImageOnPage.Source = myPNG;
)
I cant find a way to make PNG-data to a bitmap. With jpegs i could do something like
using (var stream = new MemoryStream(data, 0, x, true, true)) {
var wbp = new WriteableBitmap(1, 1);
wbp.LoadJpeg(stream);
profileImage.Source = wbp;
}
(sorry, code not testet)
I tried to look around and find the PNG Writer Library - but i still didn't find a way to do something to convert my internal PNG to a useable Bitmap for Setting the Image.Source.
Any help appreciated!

Categories

Resources