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);
Related
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);
}
I have valid base64 image . I Convert it to image .
For saving with Image.Save(Path)
I have Gdi+ error .
when i try to save with bitmap . the image will save but the image is complete black Like
And here is my code
var encode = EncodeBase64(model.Base64Photo);
//model.Base64Photo = model.Base64Photo.Replace("data:image/png;base64,", "").Replace("data:image/jpeg;base64,", "");
//var imageBytes = Convert.FromBase64String(encode);
var ms = new MemoryStream(encode);
var returnImage = Image.FromStream(ms);
var bitmap = new Bitmap(returnImage);
bitmap.Save($#"C:\inetpub\wwwroot\Dropbox\Websites\2.fidilio.com\Storage\Images\animal\storage\images\animal\{model.Name}-{model.Email}.jpg", ImageFormat.Jpeg);
bitmap.Dispose();
public byte[] EncodeBase64(string data)
{
string s = data.Trim().Replace(" ", "+").Replace("-", "+").Replace("/", "+");
if (s.Length % 4 > 0)
s = s.PadRight(s.Length + 4 - s.Length % 4, '=');
return Convert.FromBase64String(s);
}
I confused so much that where is the problem
It looks like you're making memory stream from string, am I right? You should make memory stream from byte array, like this.
string s = "iVBORw0KGgoAAAANSUhEUgAAAHgAAAB4CAAAAAAcD2kOAAACOklEQVR4Ae3YhbIdIQwA0H7YBshzd3d3d7sKJO+vqwxzty4L7UyTkfU9K0CAN/iXQmCBBf5XYIEFFlhggQXeeqr9dDxvVgi/2F+IeoVw/VfgWoVw7VfgF4H/HHbE5L+uEZNLBnt7c3Rao6+w3t0cntUpEeyfJzRAzxF96b5MalB9p5QEdq3RAhG1virL8YgKR6qG+aj4uK5G2q7kxiMw7ZPAK/BpA/a55MYjpq/hUsBrAda9NV+GwxE90EwB07kKW7BSeuV4BBYpSal2U+GVDd5RSW4P67A7CUw3xmAoRV/71rDKiRoQXoKwrU65BB8qRN1X94lg/9KjQ/kaarkyHAp7GtjyNoQdsMOd8DqgGrUuGezawyq8cs+zj66zIxr1BSVMi3waq9QiR/j1TCHMkU0Axz6Xn47l6+g1fFp+7tem6yEtTHdoQmU2B56988R3QwphgxP3QHi1wCCryZOn+svVUpdCPdBwiWFf69UYQqnu3h4NBhGOOHmfi/cBY5hPbZkaty4pHOqOwnIYfU0Zepl0obEcsEBZurc0C+UX7nnyWWD/0GU6DxZbnKlDz+tFxzE12HSZYN/o1xgDTjjbEIYPIR5Sk85mg50dV7Em31I+2NK1DuULljjraJEWIHR1X3xW2D93q49VaZczj4/5FAsFsOSyD8zpYXV68czlh61nIvo/50AErlUIP5D/6aDHCuHFk7OfjpMVma8WWGCBBRZYYIEFFlhggQUWWGCBBRZYYIEFFlhggQV+B9418JaaYBt6AAAAAElFTkSuQmCC";
var imageBytes = Convert.FromBase64String(s);
var ms = new MemoryStream(imageBytes);
var returnImage = Image.FromStream(ms);
var bitmap = new Bitmap(returnImage);
//bitmap.Save($#"C:\inetpub\wwwroot\Dropbox\Websites\2.fidilio.com\Storage\Images\animal\storage\images\animal\{model.Name}-{model.Email}.jpg", ImageFormat.Jpeg);
bitmap.Save(#"c:\temp\img.jpg");
bitmap.Dispose();
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!
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);
I'm trying to convert a byte array to a bitmap but it always shows me:
System.ArgumentException: Parameter is not valid.
My code is as follows:
I'm passing the bytes through a webservice with:
string DecodedString = string.Empty;
DecodedString = System.Text.Encoding.GetEncoding(1251).GetString(bytes);
sResult = sResult + "<Photo>" +XmlConvert.EncodeName(DecodedString) + "</Photo>";
and in my webPage:
byte[] bytes = (Byte[])System.Text.Encoding.GetEncoding(1251).GetBytes(XmlConvert.DecodeName(xDocument.SelectSingleNode("Response/Images/Photo").InnerText));
System.IO.MemoryStream ms = new System.IO.MemoryStream(bytes);
System.Drawing.Bitmap b = new System.Drawing.Bitmap(ms);//(System.Drawing.Image.FromStream(ms));
Try passing the string as a Base64:
string DecodedString = string.Empty;
DecodedString = System.Convert.ToBase64String(bytes)
sResult = sResult + "<Photo>" +XmlConvert.EncodeName(DecodedString) + "</Photo>";
...
byte[] bytes = System.Convert.FromBase64String(xDocument.SelectSingleNode("Response/Images/Photo").InnerText);
System.IO.MemoryStream ms = new System.IO.MemoryStream(bytes);
System.Drawing.Bitmap b = System.Drawing.Image.FromStream(ms);
You also won't need to use XmlConvert to encode/decode the string.
I did it, with the help of all of you, here is my page code
byte[] bytes = System.Convert.FromBase64String(xDocument.SelectSingleNode("Response/Images/Photo").InnerText);
System.IO.MemoryStream ms = new System.IO.MemoryStream(bytes);
System.Drawing.Bitmap b = new System.Drawing.Bitmap(ms); //(Bitmap)System.Drawing.Image.FromStream(ms);
System.Drawing.Imaging.FrameDimension frameDim;
frameDim = new System.Drawing.Imaging.FrameDimension(b.FrameDimensionsList[0]);
int NumberOfFrames = b.GetFrameCount(frameDim);
string[] paths = new string[NumberOfFrames];
for (int i = 0; i < NumberOfFrames; i++)
{
b.SelectActiveFrame(frameDim, i);
System.Drawing.Bitmap bmp = new System.Drawing.Bitmap(b);
paths[i] = imagePathfile.Remove(imagePathfile.Length - 4, 4) + i.ToString() + ".gif";
bmp.Save(paths[i], System.Drawing.Imaging.ImageFormat.Gif);
//bmp.Save(Response.OutputStream, System.Drawing.Imaging.ImageFormat.Gif);
bmp.Dispose();
}
Image1.Src = paths[0];
//Check if there's more than 1 image cause its a TIFF
if (paths.Length>1)
{
Image2.Src = paths[1];
}
I had a similar problem recently, but using Silverlight. I ended up needing to create a Custom HTTP Handler in order to pass the byte[] that defined the image back as a stream.
See http://www.dotnetcurry.com/ShowArticle.aspx?ID=220
Edit: This allows you to avoid worrying about XML encoding, and passes the image back in Binary form... YMMV
According to MSDN:
ArgumentException - The stream does not have a valid image format
I believe your problem is in the original byte[] array you are passing to the web service.
According to one of your comments, you did:
System.IO.FileStream fs = new System.IO.FileStream(sPath, System.IO.FileMode.Open, System.IO.FileAccess.Read);
int streamLength = Convert.ToInt32(fs.Length);
bytes = new byte[streamLength];
fs.Read(bytes, 0, streamLength);
fs.Read returns the number of bytes that have been read into the byte array; it doesn't always read the entire file!
Try using the StreamFile method from http://www.dotnetspider.com/resources/4515-convert-file-into-byte-array.aspx. (First result of Google search)
Try this:
byte[] bytes = System.Convert.FromBase64String(xDocument.SelectSingleNode("Response/Images/Photo").InnerText);
System.Drawing.ImageConverter imageConverter = new System.Drawing.ImageConverter();
Image image = imageConverter.ConvertFrom(bytes) as Image;
System.Drawing.Bitmap b = new System.Drawing.BitMap(image);
EDIT
Take a look at this:
Transfer any files on Web services by c#
actually i had been meet this problem, In my case, when i use IE browser, it is ok but when use another browser it always have the same error.
"Parameter is not valid exception is always happening in the same line of code:
System.Drawing.Image.FromStream(ms));"
So i think it seems this issue depend on browser and type of image (JPEG,JPEG2000).
Here is some code I used converting bytes to an image for a unit test:
protected override Image LoadImage()
{
//get a temp image from bytes, instead of loading from disk
//data:image/gif;base64,
byte[] bytes = Convert.FromBase64String("R0lGODlhAQABAIAAAAAAAAAAACH5BAAAAAAALAAAAAABAAEAAAICTAEAOw==");
Image image;
using (MemoryStream ms = new MemoryStream(bytes))
{
image = Image.FromStream(ms);
}
return image;
}
To my understanding, the image can not be shown because the format of the image's bytes is not correct. Every image format has its own head or something.