C# Image to base64 - c#

I have a base64 image and i have to convert it into Image. I am doing this using this code:
public static Image ConvertBase64StringToImage(string imageBase64String)
{
var imageBytes = Convert.FromBase64String(imageBase64String);
var imageStream = new MemoryStream(imageBytes, 0, imageBytes.Length);
imageStream.Write(imageBytes, 0, imageBytes.Length);
var image = Image.FromStream(imageStream, true);
return image;
}
Then i have to convert this Image into base64 again. Im using this code:
public static string ConvertImageToBase64String(Image image)
{
var imageStream = new MemoryStream();
image.Save(imageStream, ImageFormat.Png);
imageStream.Position = 0;
var imageBytes = imageStream.ToArray();
return Convert.ToBase64String(imageBytes);
}
After converting the original base64Image to image and again to base64, it loses quality.The Original base64 image is 1676 in length and after conversion it has 1660 in length.
I need the same image after conversion because i have to compare it. Any ideas how to do it without losing quality?

According to this page although PNG files are lossless, you can specify how much file compression to use when storing. IMO, as long as the Image comes out the same (you can compare them using some sort of MD5 tool), it doesn't matter if the size of the file is different when you save it, as the actual image is still the same as the original.

This is how to convert and compare your images, if the result from CompareImages is zero, it means that they are equal or very similar.
static void Main(string[] args)
{
Image img = new Bitmap("Koala.jpg");
string img64Bit = ConvertImageToBase64String(img);
Image newImg = ConvertBase64StringToImage(img64Bit);
newImg.Save("KoalaCopy.jpg");
Console.WriteLine(CompareImages(img, newImg));
Console.ReadLine();
}
public static string ConvertImageToBase64String(Image image)
{
using (MemoryStream ms = new MemoryStream())
{
image.Save(ms, image.RawFormat);
return Convert.ToBase64String(ms.ToArray());
}
}
public static Image ConvertBase64StringToImage(string image64Bit)
{
byte[] imageBytes = Convert.FromBase64String(image64Bit);
return new Bitmap(new MemoryStream(imageBytes));
}
public static int CompareImages(Image i1, Image i2)
{
string img1 = ConvertImageToBase64String(i1);
string img2 = ConvertImageToBase64String(i2);
return String.Compare(img1, img2);
}

Related

A generic error occurred in GDI+ Drawings.AddPicture using EPPlus

I want to add a picture in Excel. I use the library EPPLus. It is necessary to obtain an image of the BASE64 format and inserted into the cell in Excel
My Code:
using (System.Drawing.Image img = Base64ToImage(base64String))
{
ExcelPicture excelImage = null;
if (img != null)
{
ERROR HERE excelImage = worksheet.Drawings.AddPicture("Title", img);
excelImage.From.Column = 1;
excelImage.From.Row = 1;
excelImage.SetSize(100, 100);
}
}
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;
}
}
From MSDN:
You must keep the stream open for the lifetime of the Image.
I don't think you need to enclose MemoryStream in using

Convert Base64 String to Bitmap or Image Xamarin or Android [duplicate]

This question already has answers here:
C# Base64 String to JPEG Image
(4 answers)
Closed 6 years ago.
I'm trying to convert a Base64 string to an image and set ImageView using the same image. I know how to get it done in java, but I'm having a trouble in C#. Anyone have an idea of how to get it done in C#?
Some of the code I've tried;
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;
}
}
Base64 to Bitmap :
public Bitmap Base64ToBitmap(String base64String)
{
byte[] imageAsBytes = Base64.Decode(base64String, Base64Flags.Default);
return BitmapFactory.DecodeByteArray(imageAsBytes, 0, imageAsBytes.Length);
}
Bitmap to Base64 :
public String BitmapToBase64(Bitmap bitmap)
{
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
bitmap.Compress(Bitmap.CompressFormat.Png, 100, byteArrayOutputStream);
byte[] byteArray = byteArrayOutputStream.ToByteArray();
return Base64.EncodeToString(byteArray, Base64Flags.Default);
}
Image to Base64 String,
online conversion - here
public string ImageToBase64(Image image,
System.Drawing.Imaging.ImageFormat format)
{
using (MemoryStream ms = new MemoryStream())
{
// Convert Image to byte[]
image.Save(ms, format);
byte[] imageBytes = ms.ToArray();
// Convert byte[] to Base64 String
string base64String = Convert.ToBase64String(imageBytes);
return base64String;
}
}
Base64 String to Image,
online conversion - here
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;
}
I'm assuming that your encoded data is some bitmap format? If so, you should be able to do something like this:
public Bitmap 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))
{
Bitmap image = BitmapFactory.FromStream(ms, true);
return image;
}
}

Is it possible to create a base64 string which has all frames of a multi page tiff file?

Converting a multi page tiff file to base64 string by using known conversion methods seems to contain just a single page of it.
I'm getting the multi page tiff file from local disk:
Image multiPageImage = Image.FromFile(fileName);
Converting it to base64 string:
base64string = ImageToBase64(multiPageImage, ImageFormat.Tiff);
public static string ImageToBase64(Image image, ImageFormat format)
{
using (MemoryStream ms = new MemoryStream())
{
// Convert Image to byte[]
image.Save(ms, format);
byte[] imageBytes = ms.ToArray();
// Convert byte[] to Base64 String
string base64String = Convert.ToBase64String(imageBytes);
image.Dispose();
return base64String;
}
}
Then converting base64 to image back and saving it on the local disk to control the result:
public static Image ConvertBase64ToImage(string base64string)
{
byte[] bytes = Convert.FromBase64String(base64string);
Image image;
using (MemoryStream ms = new MemoryStream(bytes))
{
image = Image.FromStream(ms);
image.Save(#"C:\newTiff.tiff", ImageFormat.Tiff);
}
return image;
}
But result image has only single frame. That's why I'm asking if it is possible to have all frames in base64 string?
You are doing lot of unnecessary stuff just for reading a file and write it back to disk.
You can read all the content of file like this
var data = File.ReadAllBytes("image.tiff")
and then use Convert.ToBase64String(data) to convert it to a base 64 string.
var data = File.ReadAllBytes("image.tiff");
var result = Convert.ToBase64String(data);
then you can convert it back to it's byte representation and save it to disk.
var bytes = Convert.FromBase64String(result);
File.WriteAllBytes("image2.tiff", bytes);
File.ReadAllBytes()
Convert.ToBase64String()

I can' t use Image to Base64 String function

I'm making multi client chat server(done).
but I want to add image send.
I used this method when sending a message
client1 write message and getbyte -> Server -> getstring
So I'm coding like this (I can't this part)
load image -> ImageToBase64(image) -> getbyte --> server --> getstring-> Base64ToImage
Client Send part
how can i use this function and this method can be run.
private void button1_Click(object sender, EventArgs e)
{
Image screen;
screen=Image.FromFile("C:\\Users\\User\\Desktop\\Paint.bmp");
screentext = ImageToBase64(screen); //actually I do not know what parameter should be here
StreamWriter wrthr = new StreamWriter(#"C:\Users\User\Desktop\giden.txt");
wrthr.Write(screentext);
wrthr.Close(); // result empty txt
}
public string ImageToBase64(Image image, System.Drawing.Imaging.ImageFormat format)
{
using (MemoryStream ms = new MemoryStream())
{
// Convert Image to byte[]
image.Save(ms, format);
byte[] imageBytes = ms.ToArray();
// Convert byte[] to Base64 String
string base64String = Convert.ToBase64String(imageBytes);
return base64String;
}
}
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;
}
EDIT: There are two problems here...
Picking a second argument to ImageToBase64
It's up to you - do you want to keep it as a BMP file? If so, you don't really need to go via an Image at all... just load the bytes from Paint.bmp, and convert them directly into Base64:
byte[] bytes = File.ReadAllBytes(#"C:\Users\User\Desktop\Paint.bmp");
File.WriteAllText(#"C:\Users\User\Desktop\giden.txt",
Convert.ToBase64String(bytes));
Or you may wish to choose a different format, e.g. PNG or JPEG, e.g.
string screentext = ImageToBase64(screen, ImageFormat.Png);
(It's not clear where screentext is declared at the moment, but it should almost certainly be a local variable.)
Converting from base64...
This is the problem:
MemoryStream ms = new MemoryStream(imageBytes, 0,
imageBytes.Length);
// Convert byte[] to Image
ms.Write(imageBytes, 0, imageBytes.Length);
You don't need the Write call, and it's actively harmful here:
You've constructed the MemoryStream with imageBytes, so it already contains that data
By writing to the stream, you've moved the "cursor" to the end... so there's nothing to read
Just use:
public Image Base64ToImage(string base64String)
{
// Convert Base64 String to byte[]
byte[] imageBytes = Convert.FromBase64String(base64String);
MemoryStream ms = new MemoryStream(imageBytes);
return Image.FromStream(ms, true);
}

Converting image to base64

I have the following code to convert image to base64:
private void btnSave_Click(object sender, RoutedEventArgs e)
{
StreamResourceInfo sri = null;
Uri uri = new Uri("Checked.png", UriKind.Relative);
sri = Application.GetResourceStream(uri);
BitmapImage bitmap = new BitmapImage();
bitmap.SetSource(sri.Stream);
WriteableBitmap wb = new WriteableBitmap(bitmap);
MemoryStream ms = new MemoryStream();
wb.SaveJpeg(ms, bitmap.PixelWidth, bitmap.PixelHeight, 0, 100);
byte[] imageBytes = ms.ToArray();
base64 = System.Convert.ToBase64String(imageBytes);
}
And the following code to get Bitmap image form base 64:
public static BitmapImage base64image(string base64string)
{
byte[] fileBytes = Convert.FromBase64String(base64string);
using (MemoryStream ms = new MemoryStream(fileBytes, 0, fileBytes.Length))
{
ms.Write(fileBytes, 0, fileBytes.Length);
BitmapImage bitmapImage = new BitmapImage();
bitmapImage.SetSource(ms);
return bitmapImage;
}
}
So when i convert and deconvert it is blank.
I know that deconverter works, because, when i give him exact string:
string base64="iVBORw0KGgoAAAANSUhEUgAAACQAAAAkCAQAAABLCVATAAACH0lEQVR42q3WoZKrMBQGYGRkIpHEoY9DMrh1nUGtzxPcGV7gCsTaK3iBCqa2ipmrVqLrWrmytjL3nBwoEGD30ja/6JaSj/wp3SEIXjpUoB+Oeg0zpoR+NsyoDVOgi39cbYHAy4MQTc0wOYZepxRBUkn9UxxEiNnXxyYwd6w/438hSddHJilv1tqv664Shle1DeJaJihPV9uNQ+NWBRK2QVSr+GjtaFzOIpdjKFShnoY+Gv0N0u0OVLexY48NQ+68JchdpQu/o1piVMu6faJdwjNWIAYyl55bqGUtbndO53TzCIpUpCkdlEm+V3J3Ir8r3uops2+FkTmvx832IGJwN97xS/5Ti0LQ/WLwtbxMal2ueAwvc2c8CAgSJip5U4+tKHECMlUzq2UcA9EyROuJi6/71dtzWAfVcq0Jw1CsYh13kDDteVoirE+zWtLVinQ8ZAS5YlVlvRHWfi3pakUQL0OOwmp/W/vN6Gt5zBIkzEezxnCtMJsxDIECTYmhp3bej4HHzaalNMyAnzE0UBKp6Z1Do2pwd3JkAH6CxlTs/bZOZ661yMwhohDLQqREMWz8UAvWoUQleggehG5dSPUbv28GJlnKHGJsqPi7vuG/MGTyCGslOtkCOayrGOa/indajdudb6FUpXoepgiLHIIMriddyzrkMBhGAqlOH4U2hKCT2j0NdU8jFbzpZ3LQlh9srPqEQ1Y9lEP2CVa99KHvH8mnrGGdl9V9AAAAAElFTkSuQmCC";
Which is my Checked.png converted in online converter. It decompreses perfectly.
And this is my base64, which i get by converting:
"/9j/4AAQSkZJRgABAQEAYABgAAD/2wBDAAEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQH/2wBDAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQH/wAARCAAkACQDASIAAhEBAxEB/8QAHwAAAQUBAQEBAQEAAAAAAAAAAAECAwQFBgcICQoL/8QAtRAAAgEDAwIEAwUFBAQAAAF9AQIDAAQRBRIhMUEGE1FhByJxFDKBkaEII0KxwRVS0fAkM2JyggkKFhcYGRolJicoKSo0NTY3ODk6Q0RFRkdISUpTVFVWV1hZWmNkZWZnaGlqc3R1dnd4eXqDhIWGh4iJipKTlJWWl5iZmqKjpKWmp6ipqrKztLW2t7i5usLDxMXGx8jJytLT1NXW19jZ2uHi4+Tl5ufo6erx8vP09fb3+Pn6/8QAHwEAAwEBAQEBAQEBAQAAAAAAAAECAwQFBgcICQoL/8QAtREAAgECBAQDBAcFBAQA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fff8A/wAE7v8AgpB+1H/wTJ+Omn/Gv9mzxpLp9veT6ba/Ez4Wa1NdXXwy+L/hayunmPhzxx4eS4ijnmhjuL1dC8UaebXxX4Unvry58P6tZi+1GG7AP9Q3/gpJ+2p+zz/wQi/4JraUnww8MeHNE1Lwp4PsfgV+x58FbcKIvEPju20OSDR9R1i3iaG81Dw34RiSbx98U/Ed3PBe69Ik1nc6w3jPxro7ah/kLfEnx946+L/xB8b/ABV+JviXVvG3xF+I/ivXvG/jrxdrlws+r+JfFfibU7nV9c1nUZQsStdX+o3dxcyCKKG3jMnlW0ENvHFGv6ff8Fgf+CqPxQ/4K0ftQQfHDxdoEnw7+HHgrwxZeCfgx8HY/EDeI7H4f6AUhv8AxNfXeqrY6Tba34q8X+JjcalrmvpoumS3OmWnhnw+8Mtj4YsGH5ReT9PzNAHF6guy4K4wdi5HXrmip9YXbesP+mcfr6UUAdHb+NTFbwQ3Hhnw5qE0MUcT310fEUd1ciKNI0e4Fh4hsrRptqDzJY7WOSeQvNO0szvI0v8AwnEX/QneFf8Av74t/wDmroooAP8AhOIv+hO8K/8Af3xb/wDNXSjxzECD/wAIb4UODnBl8XYPsceLAcH2IPoRRRQByWp6g+p3kl21taWm8KqW1lE0UEUaDaiKZZJriUgcGa6uLi4fjzJnwMFFFAH/2Q=="
My problem is that string which i get as base64 from my code - is incorrect *What i did wrong?*
What about trying:
public static BitmapImage base64image(string base64string)
{
byte[] fileBytes = Convert.FromBase64String(base64string);
using (MemoryStream ms = new MemoryStream(fileBytes))
{
Image streamImage = Image.FromStream(ms);
context.Response.ContentType = "image/jpeg";
streamImage.Save(context.Response.OutputStream, ImageFormat.Jpeg);
return streamImage;
}
}
I agree with Alexei that your code for reading the image in does look a little strange. I've recently written some code for a similar task that I was doing which might point you in the right direction:
string fileContent = null;
/* Check the file actually has some content to display to the user */
if (uploadFile != null && uploadFile.ContentLength > 0)
{
byte[] fileBytes = new byte[uploadFile.ContentLength];
int byteCount = uploadFile.InputStream.Read(fileBytes, 0, (int)uploadFile.ContentLength);
if (byteCount > 0)
{
fileContent = CreateBase64Image(fileBytes);
}
}
private string CreateBase64Image(byte[] fileBytes)
{
Image streamImage;
/* Ensure we've streamed the document out correctly before we commit to the conversion */
using (MemoryStream ms = new MemoryStream(fileBytes))
{
/* Create a new image, saved as a scaled version of the original */
streamImage = ScaleImage(Image.FromStream(ms));
}
using (MemoryStream ms = new MemoryStream())
{
/* Convert this image back to a base64 string */
streamImage.Save(ms, System.Drawing.Imaging.ImageFormat.Png);
return Convert.ToBase64String(ms.ToArray());
}
}
not an answer: more of a long comment ... OP states that decoding code works perfectly fine, also it looks suspicios. Also code assumed to be verified to work on PNG images, but saving code explicitly produces valid JPG with SaveJpeg call...
Your code that creates stream for reading looks strange - you create stream over existing byte array, than write the same bytes into that stream, and that pass that stream without seeking back to 0 to some method.
Potential fix (assuming BitampImage can accept JPG stream):
don't call Write at all as stream already have the bytes you want
set ms.Position = 0 after writing to the stream.
Note: I'm not sure if it is OK to dispose stream that is a source for BitmapImage, you may need to remove using too.

Categories

Resources