saving image with bitmap issue - c#

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

Related

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

After Encode to base64 image rotated by 90 degres

in my app I'm uploading images to server. I encode image from my WP 8.1 and send it to server. Sending and receiving work well but I have problem with image. I don't know why but whem I uploaded the image photographed on portrait after decoding is this image rotated by 90 degrees. Landscapes images are good, but portrait are rotated. Here is my encode and decode code
Encode:
private async Task<string> StorageFileToBase64(StorageFile file)
{
string Base64String = "";
if (file != null)
{
IRandomAccessStream fileStream = await file.OpenAsync(FileAccessMode.Read);
var reader = new DataReader(fileStream.GetInputStreamAt(0));
await reader.LoadAsync((uint)fileStream.Size);
byte[] byteArray = new byte[fileStream.Size];
reader.ReadBytes(byteArray);
Base64String = Convert.ToBase64String(byteArray);
}
return Base64String;
}
Decode image on server
public void ShowImg(string b64)
{
byte[] imageBytes = Convert.FromBase64String(b64);
// Convert byte[] to Image
var ms = new MemoryStream(imageBytes, 0, imageBytes.Length);
Image image = Image.FromStream(ms, true);
f.pictureBox1.Image = image;
}
string startExpression = "data:image/png;base64,";
using (var ms = new MemoryStream())
{
ms.Flush();
System.Drawing.Image imageIn = System.Drawing.Image.FromFile(fileName);
ms.Position = 0;
imageIn.RotateFlip(System.Drawing.RotateFlipType.Rotate90FlipX);
imageIn.Save(ms, System.Drawing.Imaging.ImageFormat.Png);
var bytes= ms.ToArray();
string fileBase = Convert.ToBase64String(bytes);
var base64= startExpression + fileBase;
imageIn.Dispose();
ms.Dispose();
}

Convert images to PNG after reading media item from Sitecore

This is code that i have now implemented:
string image = String.Empty;
ImageField imageField = itm.Fields["image"];
MediaItem mediaItem = imageField.MediaItem;
if (mediaItem != null)
{
Stream stream = mediaItem.GetMediaStream();
Image img = Image.FromStream(stream);
Bitmap bmp = new Bitmap(img, 188, 122);
ImageConverter converter = new ImageConverter();
Byte[] bytes = (byte[])converter.ConvertTo(bmp, typeof(byte[]));
stream.Read(bytes, 0, bytes.Length);
image = "data:" + mediaItem.MimeType + "," + Convert.ToBase64String(bytes);
}
return image;
What i would like to do is to convert all images that come through, into PNGs. The problem that i have right now, is that GIF images that i read from Sitecore, after all the conversion that you see above, render as black images.
I tried some implementations but the result seems to be the same.
Could anyone please help?
Best regards, Marius.
It seems that the actual problem was that i had an additional line of code that was messing things up, and i am talking about this one: stream.Read(bytes, 0, bytes.Length);
This my final code that is currently working:
string image = String.Empty;
ImageField imageField = itm.Fields["image"];
MediaItem mediaItem = imageField.MediaItem;
if (mediaItem != null)
{
Stream stream = mediaItem.GetMediaStream();
Image img = Image.FromStream(stream);
Bitmap bmp = new Bitmap(img, 188, 122);
ImageConverter converter = new ImageConverter();
Stream pngStream = new MemoryStream();
bmp.Save(pngStream, ImageFormat.Png);
Byte[] bytes = (byte[])converter.ConvertTo(Image.FromStream(pngStream), typeof(byte[]));
image = "data:image/png;base64," + Convert.ToBase64String(bytes);
}
return image;
I hope that it's helpful for somebody.
Have a great day.

Convert raw images to bitmap in c#

My code currently looks like this:
if (fe == "CR2")
{
Image img = null;
byte[] ba = File.ReadAllBytes(open.FileName);
using (Image raw = Image.FromStream(new MemoryStream(ba)))
{
img = raw;
}
Bitmap bm = new Bitmap(img);
pictureBox1.Image = bm;
statusl.Text = fe;
}
When I open a RAW image the program stops and Visual Studio says:
Parameter is not valid: Image raw = Image.FromStream(new MemoryStream(ba))
Please help! How can I get a RAW file to show in a PictureBox ?
Create the bitmap like this:
Bitmap bmp = (Bitmap) Image.FromFile(open.FileName);
or without using bitmap:
this.pictureBox1.Image = Image.FromFile(open.FileName);
Example WPF:
BitmapDecoder bmpDec = BitmapDecoder.Create(new Uri(origFile),
BitmapCreateOptions.DelayCreation, BitmapCacheOption.None);
BitmapEncoder bmpEnc = new BmpBitmapEncoder();
bmpEnc.Frames.Add(bmpDec.Frames[0]);
Stream ms = new MemoryStream();
bmpEnc.Save(ms);
Image srcImage = Bitmap.FromStream(ms);
You're actually disposing an Image by specifying using (Image raw = Image.FromStream(new MemoryStream(ba))) later assigning the Disposed instance of image to picturebox which leads to this exception. To make to work you've to either don't dispose or clone the image.
Bitmap raw = Image.FromStream(new MemoryStream(ba) as Bitmap;
pictureBox1.Image = raw;
Or simply Clone
using (Image raw = Image.FromStream(new MemoryStream(ba)))
{
img = raw.Clone() as Bitmap;
}
Both of the above should work
you try this code :
private static void SaveImageToRawFile(string strDeviceName, Byte[] Image, int nImageSize)
{
string strFileName = strDeviceName;
strFileName += ".raw";
FileStream vFileStream = new FileStream(strFileName, FileMode.Create);
BinaryWriter vBinaryWriter = new BinaryWriter(vFileStream);
for (int vIndex = 0; vIndex < nImageSize; vIndex++)
{
vBinaryWriter.Write((byte)Image[vIndex]);
}
vBinaryWriter.Close();
vFileStream.Close();
}
private static void LoadRawFile(string strDeviceName, out Byte[] Buffer)
{
FileStream vFileStream = new FileStream(strDeviceName, FileMode.Open);
BinaryReader vBinaryReader = new BinaryReader(vFileStream);
Buffer = new Byte[vFileStream.Length];
Buffer = vBinaryReader.ReadBytes(Convert.ToInt32(vFileStream.Length));
vBinaryReader.Close();
vFileStream.Close();
}

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/8QAtRAAAgEDAwIEAwUFBAQAAAF9AQIDAAQRBRIhMUEGE1FhByJxFDKBkaEII0KxwRVS0fAkM2JyggkKFhcYGRolJicoKSo0NTY3ODk6Q0RFRkdISUpTVFVWV1hZWmNkZWZnaGlqc3R1dnd4eXqDhIWGh4iJipKTlJWWl5iZmqKjpK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Xm/4Jg6V8PfgkPhtqfwYT4ey+EfgFrOleDorLxX+xt8SNA8Jnwz4Ot4fh9pmseE9d8E6x8M2t9Jt9T+HEOveHvD/jvwbY2+l2uq6n4D8Q6Vrd3/kEQxfuYiMcxp3PdB+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