Upload image as byte array to server in folder - c#

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

Related

How to solve 'Could not find a part of the path..' issue on server

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

Saving an image from bytes

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

Image to string text in 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!

How to generate a zip with a dat file and a txt file with C#

I need to create a file txt and a file with extension dat. After that I want to compress these files into a zip file and to download it.
My problem is that I don't want to save the files before download. So, can I create and download the zip without creating files on server?
I used MemoryStream. Below you can find the code:
public ZipOutputStream CreateZip(MemoryStream memoryStreamControlFile, MemoryStream memoryStreamDataFile)
{
using (var outputMemStream = new MemoryStream())
{
using (var zipStream = new ZipOutputStream(baseOutputStream))
{
zipStream.SetLevel(3); // 0-9, 9 being the highest level of compression
byte[] bytes = null;
// .dat
var nameFileData = CreateFileName("dat");
var newEntry = new ZipEntry(nameFileData) { DateTime = DateTime.Now };
zipStream.PutNextEntry(newEntry);
bytes = memoryStreamDataFile.ToArray();
var inStream = new MemoryStream(bytes);
StreamUtils.Copy(inStream, zipStream, new byte[4096]);
inStream.Close();
zipStream.CloseEntry();
// .suc
var nameFileControl = CreateFileName("suc");
newEntry = new ZipEntry(nameFileControl) { DateTime = DateTime.Now };
zipStream.PutNextEntry(newEntry);
bytes = memoryStreamControlFile.ToArray();
inStream = new MemoryStream(bytes);
StreamUtils.Copy(inStream, zipStream, new byte[4096]);
inStream.Close();
zipStream.CloseEntry();
// .zip
zipStream.IsStreamOwner = false;
zipStream.Close();
outputMemStream.Position = 0;
return zipStream;
}
}
}
I assume you are working with ASP.Net ?
You can put the file contents (stream, etc...) in a byte array, then output that directly to the user in the response, like :
string fileType = "...zip...";
byte[] fileContent = <your file content> as byte[];
int fileSize = 1000;
string fileName = "filename.zip";
Response.AddHeader("Content-Disposition", "attachment;filename=\"" + fileName + "\"");
Response.ContentType = fileType;
Response.OutputStream.Write(fileContent, 0, fileSize);

Image corrupt when trying to convert B64 string to Image using C#

I'm trying to convert a stream to image using C#, but the image is appearing corrupt.
Here is how i'm getting the BaseString representation
byte[] imageArray = System.IO.File.ReadAllBytes(#"C:\Users\jay.raj\Desktop\images\images\tiger.jpg");
string base64ImageRepresentation = Convert.ToBase64String(imageArray);
Now I'm passing this to a function which converts it into Stream and tries to convert it into image file.
byte[] byteArray = Encoding.ASCII.GetBytes(mySettingInfo.FileToUpload);
MemoryStream stream = new MemoryStream(byteArray);
UtilityHelper.UploadImageFormDevice(stream, ref ss);
Here is the UploadImageFormDevice function:
public static ResponseBase UploadImageFormDevice(Stream image, ref string imageName)
{
ResponseBase rep = new ResponseBase();
try
{
string filname = imageName;
string filePath = #"C:\Users\jay.raj\Desktop\Upload\";
if (filname == string.Empty)
filname = Guid.NewGuid().ToString() + ".jpg";
filePath = filePath + "\\" + filname;
FileStream fileStream = null;
using (fileStream = new FileStream(filePath, FileMode.Create, FileAccess.Write, FileShare.None))
{
const int bufferLen = 1024;
byte[] buffer = new byte[bufferLen];
int count = 0;
while ((count = image.Read(buffer, 0, bufferLen)) > 0)
{
fileStream.Write(buffer, 0, count);
}
fileStream.Close();
image.Close();
}
imageName = filname;
}
catch (Exception ex)
{
rep.Code = 1000;
rep.Message = "Server Error";
}
return rep;
}
As #naivists wrote try replace this line:
byte[] byteArray = Encoding.ASCII.GetBytes(mySettingInfo.FileToUpload);
To this line:
byte[] byteArray = Convert.FromBase64String(mySettingInfo.FileToUpload);
It looks like you want to transfer a file from #"C:\Users\jay.raj\Desktop\images\images\tiger.jpg" to #"C:\Users\jay.raj\Desktop\Upload\" + "\\" + Guid.NewGuid().ToString() + ".jpg".
In your case you read the file as a byte array, convert it into a base 64 coded string and then again into a byte array. This is unnecessary and error prone. In your case you missed the decoding.
If you ignore for a moment that it is an image and see it just as a bunch of bytes things might get easier.
string srcPath = #"C:\Users\jay.raj\Desktop\images\images\tiger.jpg";
string dstPath = #"C:\Users\jay.raj\Desktop\Upload\" + "\\" + Guid.NewGuid().ToString() + ".jpg";
byte[] imageArray = System.IO.File.ReadAllBytes(srcPath);
System.IO.File.WriteAllBytes(dstPath, imageArray);

Categories

Resources