I am trying to create an API which will save an image at a given location .
Below is my Code for that
Image image = Image.FromFile(#"C:\Users\abc\Desktop\img-logo.jpg");
byte[] bytes = (byte[])(new ImageConverter()).ConvertTo(image, typeof(byte[]));
string str = Convert.ToBase64String(bytes);
Save_Application_Image("12004", str);
and the method in API
public void Save_Application_Image(string staffCode , string bytearray)
{
try
{
byte[] bytes = Convert.FromBase64String(bytearray);
file_path = "~/uploads/" + file_name;
FileStream file = File.Create(HttpContext.Current.Server.MapPath(file_path));
file.Write(bytes, 0, bytes.Length);
file.Close();
}
catch(Exception ex)
{
logger.LogError(ex);
}
finally
{
}
}
This api has to be called from Android Application so I will receive two string parameter.
It is saving the file perfectly but file is not readable. No preview for image file.
What is the right approach for this ?
I'm unsure of how the ImageConverter works, but I've used this before to convert Images to byte[]:
Image image = Image.FromFile(#"C:\Users\abc\Desktop\img-logo.jpg");
using (var stream = new MemoryStream())
{
image.Save(stream);
string savedImage = Convert.ToBase64String(stream.ToArray());
Save_Application_Image("12004", str);
}
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);
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;
}
}
I have web application which will convert image to base64 string. pass it to WCF service and serivce methods will convert the string back to png image.
Client Side (Convert Image to Base 64)
public static string ImageToBase64(string path)
{
using (Image image = Image.FromFile(path))
{
using (MemoryStream m = new MemoryStream())
{
image.Save(m, image.RawFormat);
byte[] imageBytes = m.ToArray();
// Convert byte[] to Base64 String
string base64String = Convert.ToBase64String(imageBytes);
return base64String;
}
}
}
WCF Serive Method
CommonDataManager.Base64ToImage(designImage).Save(designQuotePath + "/" + "Request_Quote_" + objQuote.Customer_Id.ToString(), ImageFormat.Png);
public static Image Base64ToImage(string base64String)
{
Image image = null;
try
{
byte[] imageBytes = System.Convert.FromBase64String(base64String);
using (MemoryStream ms = new MemoryStream(imageBytes, 0, imageBytes.Length))
{
image = Image.FromStream(ms, true);
}
}
catch (Exception ex)
{
LogManager.LogException(ex, "Base64ToImage");
}
return image;
}
Issues :
It is giving output as normal file not .png file.
Is there any special things need to be checked before sending base64 string to wcf service method as parameter ?
Thanks in advance.
You need to add the extension. Update this:
CommonDataManager.Base64ToImage(designImage).Save(designQuotePath + "/" +
"Request_Quote_" + objQuote.Customer_Id.ToString(), ImageFormat.Png);
To
CommonDataManager.Base64ToImage(designImage).Save(designQuotePath + "/" +
"Request_Quote_" + objQuote.Customer_Id.ToString() + ".png", ImageFormat.Png);
We are using Flash to send an image to the servers and upload an image. The way we're trying to do this is by sending the bytes to the server through a parameter and then converting the bytes to an image.
http://i.gyazo.com/fb8225af80ef465b0262d97f63bd54b2.png
In the image the object is sending a few different bits of information. I'm not sure if I am supposed to just receive one bit of information instead of the entire object.
So far I have the post request
string byteArray = Request["bytes"];
Then I am trying to convert it to an image
string file_name = Guid.NewGuid().ToString();
//byte[] imageBytes = Convert.FromBase64String(byteArray);
Derio.App.Model.Helper.ByteArrayToFile(file_name, Derio.App.Model.Helper.GetBytes(byteArray));
My helper method looks like -
public static class Helper
{
public static byte[] GetBytes(string str)
{
byte[] bytes = new byte[str.Length * sizeof(char)];
System.Buffer.BlockCopy(str.ToCharArray(), 0, bytes, 0, bytes.Length);
return bytes;
}
public static string ByteArrayToFile(string _FileName, byte[] _ByteArray)
{
try
{
// Open file for reading
System.IO.FileStream _FileStream =
new System.IO.FileStream(_FileName, System.IO.FileMode.Create,
System.IO.FileAccess.Write);
// Writes a block of bytes to this stream using data from
// a byte array.
_FileStream.Write(_ByteArray, 0, _ByteArray.Length);
// close file stream
_FileStream.Close();
return "true";
}
catch (Exception _Exception)
{
// Error
return "Exception caught in process:" + _Exception.ToString();
}
}
}
We've multiple different methods such as trying to convert it from Base64String to an image.
I can't for the life of me though figure out what I am doing wrong.
What happens when you try this:
string file_name = Guid.NewGuid().ToString();
string byteArray = Request["bytes"];
byte[] imageBytes = Convert.FromBase64String(byteArray);
IO.File.WriteAllBytes(file_name, imageBytes);
I want to use C# to convert a byteArray to base64string by using Convert.ToBase64String(), then I want to send this string to save using MySQL by sending post data to a PHP page. My problem is I can't convert this string back to a byteArray using this method as after this string is retrieved from the PHP page (after it got data from MySQL), it tells me that argument on method Convert.FromBase64String() was wrong.
I don't where is problem occurs, how can I solve it?
My code:
public static string BitmapToString(BitmapImage img)
{
try
{
WriteableBitmap bmp = new WriteableBitmap(img);
byte[] byteArray = null;
string str = null;
MemoryStream stream = new MemoryStream();
bmp.SaveJpeg(stream, bmp.PixelWidth, bmp.PixelHeight, 0, 100);
byteArray = stream.ToArray();
str = Convert.ToBase64String(byteArray);
return str;
}
catch (System.Exception ex)
{
Console.WriteLine(ex.StackTrace);
}
return null;
}
public static BitmapImage StringToBitmap(string str)
{
try
{
byte[] byteArray = Convert.FromBase64String(str);
Stream memStream = new MemoryStream(byteArray);
BitmapImage img = null;
MemoryStream stream = new MemoryStream(byteArray);
stream.Seek(0, SeekOrigin.Begin);
img = new BitmapImage();
img.SetSource(stream);
return img;
}
catch (System.Exception ex)
{
Console.WriteLine(ex.StackTrace);
}
return null;
}
Convert.FromBase64String() will work for Convert.ToBase64String() results but there can be inputs in your aplication which not converted to Base64String, those cases might fail.
This is not be a issue with those two methods. Check Convert.ToBase64String() result and what you get when you read it from database.