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);
Related
I'm using Zxing library to create a barcode and memory stream to save it to the server folder.
Everything works fine on local as well as a testing server, but when I publish code on client-server it won't create a barcode image nor get location of image on that server location.
Here is the code I created for this process-
var writer = new BarcodeWriter();
writer.Format = BarcodeFormat.CODE_128;// QR_CODE;
var result = writer.Write(printArray[0]);
string path = Server.MapPath("/images/code/" + ComplaintId + ".jpg");
var barcodeBitmap = new Bitmap(result);
using (MemoryStream memory = new MemoryStream())
{
using (FileStream fs = new FileStream(path, FileMode.Create, FileAccess.ReadWrite))
{
barcodeBitmap.Save(memory, ImageFormat.Jpeg);
byte[] bytes = memory.ToArray();
fs.Write(bytes, 0, bytes.Length);
}
}
This code is used to save bar code on the server location.
string ImagePath = ComplaintId + ".jpg";
imgQRcode.Src = "~/images/code/" + ImagePath;
and used this line to bind it to img tag.
it shows error like
Could not find a part of the path g:\xyz\images\code\103.jpg
this only happen on client-server not elsewhere.
---------Edit 1--------
As I was still facing issues while creating image on a host server, I made a few changes in code now. Instead of saving barcode image I'm converting it to Base64 string and using it.
Here is code changes
var barWriter = new BarcodeWriter();
barWriter.Format = BarcodeFormat.CODE_128;// QR_CODE;
var barResult = barWriter.Write("printbar");
var barcodeBitmap = new Bitmap(barResult);
string bs64 = ToBase64String(barcodeBitmap, ImageFormat.Jpeg);
and Tobase64String function
public static string ToBase64String(Bitmap bmp, ImageFormat imageFormat)
{
string base64String = string.Empty;
MemoryStream memoryStream = new MemoryStream();
bmp.Save(memoryStream, imageFormat);
memoryStream.Position = 0;
byte[] byteBuffer = memoryStream.ToArray();
memoryStream.Close();
base64String = Convert.ToBase64String(byteBuffer);
byteBuffer = null;
return base64String;
}
and function to bind base64 to image
public static string GetImageSrc(string base64Src)
{
return "data:image/png;base64," + base64Src;
}
to feed it to iTextcharp use
byte[] imageBytes = Convert.FromBase64String(bs64);
iTextSharp.text.Image img = iTextSharp.text.Image.GetInstance(imageBytes);
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);
}
Ive got a question I am having a case of rest response that is always string, it suppose to download content of the file, but there can be many different files, for example PNG, now if I'm getting a string in response is it possible to convert it back to PNG at the end, I tried something like:
byte[] array = Encoding.ASCII.GetBytes(result.data); //response content
MemoryStream ms = new MemoryStream(array);
Image i = Image.FromStream(ms);
I dont think im getting base64 string from rest looks like (part of it, and if i remmebr base64 ends with 3 === and don't have any non printable chars):
�PNG\r\n\n\0\0\0\rIHDR\0\0�\0\0\0�\b\0\0\0���\0\0\0sRGB\0���\0\0\0gAMA\0\0��\v�a\0\0\0\tpHYs\0\0t\0\0t�fx\0\0\f\aIDATx^��!x�L���Jde%�yY�D�H$�d%2��S��Hd%y�<�ӹ�B�ٝ�O�mﺔ��d����\r\0���\a�(H|\0���\a�(H|\0���\a�(H|\0���\a�(H|\0���\a�(H|\0���\a�(H|\0���\a�(H|\0���\a�(H|\0���\a�(H|\0���\a�(H|\0�\"D�WU��v������r��o#\f!��y�����K�\0�'D�O�SM�\f�����\0��Dǯ�z4�R��C�7\0��+�\0�\0Q��\0�\0Q��UU���ļO ?�������!�#J�>���|D��$>\f�|D��$>\f��7X,�?�_\v]�V�^/�=��#4$�����$:��P9
Assuming you are returning base 64 string from the API response, you can do something like this
byte[] bytes = Convert.FromBase64String(result.data);
Image image;
using (MemoryStream ms = new MemoryStream(bytes))
{
image = Image.FromStream(ms);
}
return image;
Or you can save it directly to the file
string filePath = "Image.png";
File.WriteAllBytes(filePath, Convert.FromBase64String(result.data));
EDIT 1:
How are you returning data from your web API? You could do something like this to return byte array and then use this array directly to write to stream.
var result = new HttpResponseMessage(HttpStatusCode.OK);
String filePath = HostingEnvironment.MapPath("~/imagename.png");
FileStream fileStream = new FileStream(filePath, FileMode.Open);
Image image = Image.FromStream(fileStream);
MemoryStream memoryStream = new MemoryStream();
image.Save(memoryStream, ImageFormat.Jpeg);
result.Content = new ByteArrayContent(memoryStream.ToArray());
result.Content.Headers.ContentType = new MediaTypeHeaderValue("image/png");
return result;
and on the client side you can do something like
var data = response.Content.ReadAsByteArrayAsync().Result;
Image image;
using (MemoryStream ms = new MemoryStream(data))
{
image = Image.FromStream(ms);
}
return image;
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();
}
I'm not trying to read the EXIF data on either the device or server, but the data needs to be present on the server.
I am currently sending the image to the server via converting it to a byte[] and then to base64 Convert.ToBase64(byte[]) and sending it using JSON - see code below.
But when I get the file at the other end, it doesn't have any EXIF data. If I get the image off the emulator with the fake SD card, the EXIF data exists.
Does anyone know how to upload the image and then reconstruct it at the other end so that the EXIF data stays intact?
Image to bytes to base64 to JSON
BitmapImage image = new BitmapImage();
image.SetSource(e.ChosenPhoto);
image = ResizeImage(image);
byte[] imageBytes;
using (MemoryStream ms = new MemoryStream())
{
WriteableBitmap btmMap = new WriteableBitmap(image);
System.Windows.Media.Imaging.Extensions.SaveJpeg(btmMap, ms, image.PixelWidth, Image.PixelHeight, 0, 100);
image = null;
imageBytes = ms.ToArray();
}
Base64Image imagestring = new Base64Image();
imagestring.imagestring = Convert.ToBase64String(imageBytes);
string json = JsonConvert.SerializeObject(imagestring);
JSON To base64 to byte[] to image
using (StreamReader sr = new StreamReader(inputStream))
{
postData = sr.ReadToEnd();
}
JavaScriptSerializer deserializer = new JavaScriptSerializer();
Dictionary<string, object> jsonObjects = (Dictionary<string, object>)deserializer.DeserializeObject(postData);
string base64image = jsonObjects["imagestring"].ToString();
byte[] imagebytes = Convert.FromBase64String(base64image);
BitmapImage bitmapImage = new BitmapImage();
MemoryStream ms = new MemoryStream(imagebytes);
bitmapImage.BeginInit();
bitmapImage.CacheOption = BitmapCacheOption.OnDemand;
bitmapImage.CreateOptions = BitmapCreateOptions.None;
bitmapImage.Rotation = Rotation.Rotate0;
bitmapImage.StreamSource = ms;
bitmapImage.EndInit();
bitmapImage.CreateOptions = BitmapCreateOptions.None;
WriteableBitmap wBmp = new WriteableBitmap(bitmapImage);
var encoder = new JpegBitmapEncoder();
encoder.Frames.Add(BitmapFrame.Create(wBmp));
I had to change my code completely to cut out any connection to Bitmaps or other formats, and just used byte[] through it. See code:
On the app:
ImageData imagedata = new ImageData();
byte[] imagebytes = new byte[e.ChosenPhoto.Length];
e.ChosenPhoto.Read(imagebytes, 0, int.Parse(e.ChosenPhoto.Length.ToString()));
imagedata.imagestring = Convert.ToBase64String(imagebytes);
string json = JsonConvert.SerializeObject(imagedata);
At the server:
JavaScriptSerializer deserializer = new JavaScriptSerializer();
deserializer.MaxJsonLength = 50000000;
Dictionary<string, object> jsonObjects = (Dictionary<string, object>)deserializer.DeserializeObject(postData);
string base64image = jsonObjects["imagestring"].ToString();
byte[] imagebytes = Convert.FromBase64String(base64image);
Guid imagename = Guid.NewGuid();
if (!Directory.Exists(EM.ImagePath))
Directory.CreateDirectory(EM.ImagePath);
using (FileStream sw = new FileStream(EM.ImagePath + imagename + ".jpg", FileMode.CreateNew))
{
sw.Write(imagebytes, 0, imagebytes.Length);
}