Image to string text in C# - c#

I wrote this code
MemoryStream ms = new MemoryStream();
pictureBox1.Image.Save(ms, System.Drawing.Imaging.ImageFormat.Gif);
Now I want to check ms text. How can I do that?

With this code, you can encode the image Bytes into an hexadecimal string representation:
Byte[] a = ms.ToArray();
String text = BitConverter.ToString(a);

You can try with this code....
var url = HostingEnvironment.MapPath("~/Images/" + name);
byte[] myByte = System.IO.File.ReadAllBytes(url);
using (MemoryStream ms = new MemoryStream())
{
ms.Write(myByte, 0, myByte.Length);
i = System.Drawing.Image.FromStream(ms);
System.Drawing.Image imageIn = i.GetThumbnailImage(100, 100,()=> false, IntPtr.Zero);
imageIn.Save(ms, System.Drawing.Imaging.ImageFormat.Gif);
var storedUrl = "data:image;base64," + Convert.ToBase64String(ms.ToArray());
return storedUrl;
}

I use this to send the image as string:
string path = #"C:\Users\user6\Pictures\wp\tinypotato.jpg";
string myString = Convert.ToBase64String(File.ReadAllBytes(path))
Debug.WriteLine(myString);
...
BR!

Related

How to Convert Base64 String into Png Image Mvc5 C#?

I am Trying to Convert a Base64 encoded string to A Png Image, But the Code Shows Exception of Parameter is Not Valid on Image.FromStream(). After Debugging i cam up with this error on MemoryStream Object "ReadTimeout = 'ms.ReadTimeout' threw an exception of type 'System.InvalidOperationException'" . I am stuck, Is there any Solution or Alternative to Convert String to Png in C#?
Here is My code
string code = "string";
var databytes = Encoding.Unicode.GetBytes(code);
var base64 = Convert.ToBase64String(databytes);
Byte[] Bytes = Convert.FromBase64String(base64);
//Stream bytes
MemoryStream ms = new MemoryStream(Bytes, 0, Bytes.Length);
//convert image
Image newImage = Image.FromStream(ms);
newImage.Save("~/Content/");
Try this:
byte[] bytes = Convert.FromBase64String(base64);
Image image;
using (MemoryStream ms = new MemoryStream(bytes))
{
image = Image.FromStream(ms);
}
You can convert Base64 string into png in this way:
byte[] bytes = Convert.FromBase64String(base64);
Image image;
using (MemoryStream ms = new MemoryStream(bytes))
{
image = Image.FromStream(ms);
image.Save("~/Content/", System.Drawing.Imaging.ImageFormat.Png);
}

Upload image as byte array to server in folder

my question is how to upload byte array to server ?
I am already convert it to byte array like this :
Stream stream = ContentResolver.OpenInputStream(data.Data);
Bitmap bitmap = BitmapFactory.DecodeStream(stream);
MemoryStream memStream = new MemoryStream();
bitmap.Compress(Bitmap.CompressFormat.Jpeg, 50, memStream);
byte[] picData;
picData = memStream.ToArray();
Now I want to upload picData to the server in folder "pics"
public string UploadToServer(byte[] image)
{
try
{
MemoryStream ms = new MemoryStream(image);
var i = Bitmap.FromStream(ms);
string time = DateTime.Now.ToString("dd_MM_yyyy_HH_mm_ss");
string Filename = "IMG_" + time + ".png";
string UploadPath = HttpContext.Current.Server.MapPath("~/Image");
if (!Directory.Exists(UploadPath))
Directory.CreateDirectory(UploadPath);
string NewFilePath = Path.Combine(UploadPath, Filename);
File.WriteAllBytes(NewFilePath, image);
return Filename;
}
catch (Exception)
{
throw;
}
}

how to get PNG image from this encoded png image data

I have the PNG image data like below but I can't able to decode it by using any of the decoding method.
People who have knowledge on this help me to get the image by using encoded/decoding technique of this.
"�PNG\r\n\u001a\n\0\0\0\rIHDR\0\0\u0013`\0\0\u001bf\u0001\0\0\0\0Nw�v\0\0 \0IDATx��O��H���(/�\u0017\u0006�b-tP\u001ej�U؃����4\u0005l)Y�}�Q\u001fa���9*\a���ڢgGo{\u001f\u0006\u001d_##C��\u0004:,�\u001e�\t\u001d\u0004�\u001c�0��o\n*a �\u0019��6��I���H�����o�#\u007f\u000f\"#��iF��9iƗ\u00165\0\u0010\u0011=t\u0001��\u0003d\u0003d#6#\u0006d\u0003d#6#\u0006d\u0003d#6#\u0006d\u0003d#6#\u0006d\u0003d....
It has all the png critical chunks like IHDR, IDAT, IEND.
//For Encoding
byte[] buf = File.ReadAllBytes(#"C:\Users\GPL\Desktop\Newfolder\balloon_PNG4957.png");
var s = Encoding.ASCII.GetString(buf);
File.WriteAllText(#"C:\Users\GPL\Desktop\balloon_PNG4957.txt", s);
//For Decoding
var rawdata = File.ReadAllText(#"C:\Users\GPL\Desktop\balloon_PNG4957.txt");
byte[] buf = Encoding.ASCII.GetBytes(rawdata);
var ms = new MemoryStream(buf);
var bitmap = Image.FromStream(ms); //Error
pictureBox1.Image = bitmap;
Here while decoding I am getting error - ""Parameter is not valid". "
It is called escaped string literal
try this (replace real text here after st=) like this:
string st= "�PNG\r\n\u001a\n\0\0\0\rIHDR\0\0\u0013`\0\0\u001bf...";
File.WriteAllBytes("png.png", st.Select(s => (byte) s).ToArray());
or simply convert it char by char :
var ba = new List<byte>();
foreach (var s in st)
{
ba.Add((byte) s);
}
File.WriteAllBytes("png.png", ba.ToArray());
note: for two bytes Unicode chars use another ba.Add((byte) (s>>8)); inside foreach.
this is what you need: C# escape characters in user input
see: Can I convert a C# string value to an escaped string literal
If it is a file you may read it like this and show inside pictureBox1:
var bitmap = Image.FromFile(#"filename.png");
pictureBox1.Image = bitmap;
pictureBox1.SizeMode = PictureBoxSizeMode.StretchImage;
If it is Stream or MemoryStream or byte[] use this:
byte[] buf = File.ReadAllBytes(#"filename.png");
var ms=new MemoryStream(buf);
var bitmap = Image.FromStream(ms);
pictureBox1.Image = bitmap;
pictureBox1.SizeMode = PictureBoxSizeMode.StretchImage;
It is ASCII Encoding:
byte[] buf = File.ReadAllBytes(#"filename.png");
var sb=new StringBuilder();
var s=Encoding.ASCII.GetString(buf );
textBox1.Text = buf.Length + #", " + s.Length;
File.WriteAllText("png.txt", s);
Stream mr = response.GetResponseStream();
var bitmap = Image.FromStream(mr);
Bitmap bmp = new Bitmap(bitmap);
MemoryStream ms = new MemoryStream();
bmp.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);

upload photo to server

I am using this code for upload photo:
MemoryStream photoStream = new MemoryStream();
e.ChosenPhoto.CopyTo(photoStream);
photoStream.Position = 0;
byte[] buf = photoStream.ToArray();
string str = Convert.ToBase64String(buf);
string fileBase64 = HttpUtility.UrlEncode(str);
// Send fileBase64 to server
The server then decode the base64 string and name it "test.jpt".
the problem is that paint doesn't open the image uploaded on my server.
Why ?
i think your base64 string is incorrect. I have written this code, here it is, it works:
BitmapImage a = new BitmapImage();
a.SetSource(e.ChosenPhoto);
WriteableBitmap wb = new WriteableBitmap(a);
MemoryStream ms = new MemoryStream();
wb.SaveJpeg(ms, a.PixelWidth, a.PixelHeight, 0, 50); //50 is a quality of a photo
imageBytes = ms.ToArray();
base64 = System.Convert.ToBase64String(imageBytes);

Bitmap to Base64String

i am trying to convert a bitmap to a base64 string.i can convert to from string to bitmap...but it seems like there is a problem when converting from bitmap to string.I was hoping you guys could give me a hand
public static string BitmapToString(BitmapImage image)
{
Stream stream = image.StreamSource ;
Byte[] buffer = null;
if (stream != null && stream.Length > 0)
{
using (BinaryReader br = new BinaryReader(stream))
{
buffer = br.ReadBytes((Int32)stream.Length);
}
}
return Convert.ToBase64String(buffer);
}
it gets a ArgumentNullException was unhandled
Value cannot be null.
Parameter name: inArray
when returning Convert.ToBase64String(buffer)
Help?
Try this alternative:
public string BitmapToBase64(BitmapImage bi)
{
MemoryStream ms = new MemoryStream();
PngBitmapEncoder encoder = new PngBitmapEncoder();
encoder.Frames.Add(BitmapFrame.Create(bi));
encoder.Save(ms);
byte[] bitmapdata = ms.ToArray();
return Convert.ToBase64String(bitmapdata);
}
In your solution, it is not necessary that StreamSource will always have value if it is loaded using a Uri.
First of all, it is necessary to save BitmapImage data into memory using some bitmap encoder (PngBitmapEncoder for example).
public static byte[] EncodeImage(BitmapImage bitmapImage)
{
using (MemoryStream memoryStream = new MemoryStream())
{
BitmapEncoder encoder = new PngBitmapEncoder();
encoder.Frames.Add(BitmapFrame.Create(bitmapImage));
encoder.Save(memoryStream);
return memoryStream.ToArray();
}
}
Then just encode the binary data with Base64-encoding.
const string filePath = #"...";
const string outFilePath = #"...";
const string outBase64FilePath = #"...";
// Constuct test BitmapImage instance.
BitmapImage bitmapImage = new BitmapImage();
bitmapImage.BeginInit();
bitmapImage.StreamSource = File.OpenRead(filePath);
bitmapImage.CacheOption = BitmapCacheOption.OnLoad;
bitmapImage.EndInit();
// Convert BitmapImage to byte array.
byte[] imageData = EncodeImage(bitmapImage);
File.WriteAllBytes(outFilePath, imageData);
// Encode with Base64.
string base64String = Convert.ToBase64String(imageData);
// Write to file (for example).
File.WriteAllText(outBase64FilePath, base64String);

Categories

Resources