In Unity trying to convert a Base64String to a png - c#

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);

Related

How convert Image to png with imagemagik lib in C#?

I've write a aws Lambda to convert my images.
The process of the lambda function is to take input images of any format and in the case of non-png images, convert them to jpeg otherwise add some data and convert it to png by adding transparency. Finally save the generated images on s3.
I write a function in C# using a imagemagick library in .Net Core.
I've a problem with png conversion. The result image have a dashed border!
This is my method to PNG convert.
private MemoryStream ConvertToPNG(MemoryStream inputStream)
{
MemoryStream outputStream = new MemoryStream();
inputStream.Position = 0;
using (MagickImage image = new MagickImage())
{
image.Read(inputStream);
image.Quality = 90;
image.TransformColorSpace(ColorProfile.SRGB, ColorProfile.AdobeRGB1998);
image.Settings.Compression = CompressionMethod.NoCompression;
image.Format = MagickFormat.Png64;
image.Write(outputStream);
}
return outputStream;
}
I tried with another stack, using Pillow library in py and work, generated image is great. Unfortunately I am forced to use C # and .Net for obvious reasons.
Has anyone ever had this problem?
Thanks everyone for the contribution.

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];

How to display an image in an Asp:image?

So here's the deal, I have to take a text value from sql server, that beeing a encoded image, store it in a string and then I can convert it to Image type by decoding it, the thing is, how do I display said decoded image in the asp:image thing? cuz i whas hopping that this component would have an .image property where i can just put the image and it would display it just like that but it just has .ImageUrl that would work just fine if the image was stored in my pc but it isn´t, I tried to make it a binary string and then instead of using and asp:image use img, then put the decoded image in .src by converting it to a base 64 string but i've been told that it only works with .jpg format and i have to use both .jpg and .png,
I'm new in asp.net so I may be making a dumb question but I search everywhere and I can't seem to find a clear solution, can somebody help me?
btw sorry if I'm barely understandable, English isn't my main language.
byte[] imageArray = System.IO.File.ReadAllBytes(Server.MapPath("~/App_Data/Images/client_group_logo.png"));
var imageString = imageArray != null ? Convert.ToBase64String(imageArray) : "";
var img = string.Format("data:image/jpg;base64,{0}", imageString);
ViewBag.ImagePath = img;
if you view this image.please paste this below code in your cshtml file.
<img src="#Url.Content(ViewBag.ImagePath)" />

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!

Why is Base64 string different in C# and Android

I have convert one image into base64 string and that output same with online website.
But the same image when I convert it from Android is different.
Can you please explain why C# and Android base64 strings are different for the same image.
C#.NET Code
string cImagePath = #"G:\bg-listing.png";
byte[] imagebyte = StreamFile(cImagePath);
String result = System.Convert.ToBase64String(imagebyte);
System.IO.StreamWriter outFile;
try
{
outFile = new System.IO.StreamWriter(Application.StartupPath + "//image2base641.txt",
false,
System.Text.Encoding.Default);
outFile.Write(result.ToString());
outFile.Close();
}
catch (System.Exception exp)
{
// Error creating stream or writing to it.
System.Console.WriteLine("{0}", exp.Message);
}
Android Code
Bitmap bitmapOrg = BitmapFactory.decodeResource(getResources(), R.drawable.image);
ByteArrayOutputStream bao = new ByteArrayOutputStream();
bitmapOrg.compress(Bitmap.CompressFormat.JPEG, 100, bao);
byte [] ba = bao.toByteArray();
String ba1=Base64.encodeToString(ba,Base64.DEFAULT);
Both image base64 are different.
Please help me.
There are many variants of base 64, involving line length, padding, check sums, etc. The Wikipedia article on Base64 has a nice table of variants.
My guess is that C# and Android are simply using different variants.
EDIT Based on your updated post, there are a couple of other possibilities:
Android may be modifying the .jpg file when it packages it up as a resource (however, while the resource packager is extremely aggressive regarding compression, this is probably not the case);
Android may be re-encoding the image differently than the original (two .jpg files can represent the same pixel values and not be byte-for-byte identical)
A better test would be to skip (in the Android code) the conversion from a resource to a Bitmap and back to a .jpg encoding. Just open the resource as a stream, read it directly into a byte array, and encode that in base 64.

Categories

Resources