Converting full path of Image to binary - c#

firstly, yes I know it might be a duplicate question, but really, I have applied all possible answers but nothing worked.
What I want is to convert an image selected by the user to binary format, and I'm using asp.net/c# to do such method.
Look at my codes first to do this:
if (FileUpload1.HasFile)
{
pressNumberOfTimes++;
string strname = Path.GetFileName(FileUpload1.PostedFile.FileName);
lbl_homeCarouselAdd.ID = "lbl_homeCarouselAdd" + pressNumberOfTimes;
strDiv.Append(string.Format(strname) + ",");
FileUpload1.PostedFile.SaveAs(HttpContext.Current.Server.MapPath("~/upload/") + strname);
string fullImagePath = HttpContext.Current.Server.MapPath("~/upload/") + strname;
byte[] imgdata = File.ReadAllBytes(fullImagePath);
var a = String.Join(",", lbl_homeCarouselAdd.Text += strDiv.ToString());
from what I have seen from the answers in this website and others to convert image to binary is to use this code:
byte[] imgdata = File.ReadAllBytes(fullImagePath);
which I have used in my codes.
However, all I get is an empty value for the binary, while "fullImagePath" variable holds the full bath of the selected image.
I have also used the following method, but it gave me the same empty result:
public static byte[] ImageToBinary(string _path)
{
FileStream fS = new FileStream(_path, FileMode.Open, FileAccess.Read);
byte[] b = new byte[fS.Length];
fS.Read(b, 0, (int)fS.Length);
fS.Close();
return b;
}
For more info:
This is how my web form looks like
so, the user can upload an image and then click "save image" button in order to save the selected event, and here the website should convert the image to binary format.
Concerns:
Is it possible that "upload" folder in my "VS" project is not refreshed with the new selected image is the reason behind the empty value??
Is it possible that permissions among c:\ directory is causing such error?? because I'm working on a machine given by the company I work for, and I did face some issues before regarding this.

if(FileUpload1.HasFile)
{
string filename = Path.GetFileName(FileUpload1.PostedFile.FileName);
string extension = Path.GetExtension(filename);
string contentType = FileUpload1.PostedFile.ContentType;
HttpPostedFile file = FileUpload1.PostedFile;
byte[] imgdata= new byte[file.ContentLength];
file.InputStream.Read(imgdata, 0, file.ContentLength);
}

Related

Streamed File Contains Strange Characters - An Encoding Issue

I have a WCF service end-point which generates an excel file and returns this file as a MemoryStream in the end in order to make client download the relevant file.
The file generated on the respective directory has no issues. I don't see any strange characters when I open and check it.
But, the file I returned with MemoryStream is full of strange unreadable characters.
My end-point is like that,
public Stream GetEngagementFeedFinalizeData(int workspaceId, string startDate, string endDate, Stream data)
{
try
{
string contentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;";
string extension = "xls";
string fileName = "report-" + DateTime.Now.Ticks.ToString();
string contentDisposition = string.Format(CultureInfo.InvariantCulture, "attachment; filename={0}.{1}", fileName, extension);
WebOperationContext.Current.OutgoingResponse.ContentType = contentType;
WebOperationContext.Current.OutgoingResponse.Headers.Set("Content-Disposition", contentDisposition);
//Here is some business logic and fetching data from db. Not any encoding
//related issue. The data set is assigned to a variable
//named "feedFinalizeDataTable" in the end
feedFinalizeDataTable.TableName = "Summary";
DataSet dataSet = new DataSet();
dataSet.Tables.Add(feedFinalizeDataTable);
using (ExcelPackage excelPackage = new ExcelPackage())
{
foreach (DataTable dt in dataSet.Tables)
{
ExcelWorksheet sheet = excelPackage.Workbook.Worksheets.Add(dt.TableName);
sheet.Cells["A1"].LoadFromDataTable(dt, true);
}
var path = System.IO.Path.Combine(System.AppDomain.CurrentDomain.BaseDirectory);
var filePath = path + "\\" + "New.xls";
excelPackage.SaveAs(new System.IO.FileInfo(filePath)); //This file is flawless
FileStream fs = new FileStream(filePath, FileMode.Open);
int length = (int)fs.Length;
WebOperationContext.Current.OutgoingResponse.ContentLength = length;
byte[] buffer = new byte[length];
int sum = 0;
int count;
while ((count = fs.Read(buffer, sum, length - sum)) > 0)
{
sum += count;
}
fs.Close();
return new MemoryStream(buffer); //This file is full of unreadable chars as per above shared screenshot
}
I'm using OfficeOpenXml to generate excel files.
Then, I checked both files encoding by open them with notepad. I saw that the file on the directory (the flawless one) has ANSI encoding. And, the one which is returned by the end-point (the broken one) has UTF-8 encoding.
After that, I try to change the encoding type of the stream like this,
var byteArray = System.IO.File.ReadAllBytes(filePath);
string fileStr = new StreamReader(new MemoryStream(byteArray), true).ReadToEnd();
var encd = Encoding.GetEncoding(1252); //On the other topics I saw that ANSI represented with 1252
var end = encd.GetBytes(fileStr);
return new MemoryStream(end);
But, this doesn't help too. Though some of the strange characters are replaced with some other strange characters, but as I said, streamed file is still unreadable. And, when I open it with notepad to see its encoding, I saw that its still UTF-8.
Thus, I'm kind of stuck. I have also try directly to stream the generated excel file (without writing it to a directory and then reading it) with OfficeOpenXml's built in function called .GetAsByteArray(), but the downloaded file looks exactly the same as per above screenshot.
Thanks in advance.

Fix this is not a valid bitmap file

string sDir = #"\\Q1875G\Vehicle";
NetworkCredential NCredentials = new NetworkCredential("FOLDER_ACCESS_USER", "Welcome#2020");
using (new NetworkConnection(sDir, NCredentials))
{
string path = $"{sDir}\\483";
if (!Directory.Exists(path))
Directory.CreateDirectory(path);
string fileName = "add_274400.jpg";
path = $"{sDir}\\483\\{fileName}";
byte[] byteArrayIn = imageByteArray;
using (var ms = new MemoryStream(byteArrayIn))
{
using (var fs = new FileStream(path, FileMode.Create))
{
ms.WriteTo(fs);
}
}
}
Using this code image file getting created but when I try to open it, it gives an error that this is not a valid bitmap file, or its format is not currently supported.
That's not a JPEG yet; it's the bytes of a jpeg, base64 encoded, and prefixed with a header that would make it suitable for plonking inline into an <img src= tag attribute
The jpeg data starts with the /9j so you'll have to do something like:
var b64jpeg = Encoding.ASCII.GetString(imageByteArray, 23, imageByteArray.Length - 23);
var jpegBytes = Convert.FromBase64String(b64jpeg);
Then write jpegBytes to a file. There is no need to put it in a MemoryStream first; just File.WriteAllBytes it
If this imageByteArray has been delivered to you as a string (outside the code visible in the question) it would be better to keep it as that and substring it, rather than having this "to array (in the other code), from array (in this code)" step
Side note: you don't need if (!Directory.Exists(path)) either; Directory.CreateDirectory does nothing if the directory exists, so just call it without the Exists check

How to get the ZIP file from Base64 string in Javascript?

I am trying to get the compressed ZIP file back in Javascript. I am able to convert the zip file into Base64 String format. (Zip file is in Server)
Here is my try (at Server Side)
System.IO.FileStream fs = new System.IO.FileStream(SourceFilePath + "Arc.zip", System.IO.FileMode.Open);
Byte[] zipAsBytes = new Byte[fs.Length];
fs.Read(zipAsBytes, 0, zipAsBytes.Length);
String base64String = System.Convert.ToBase64String(zipAsBytes, 0, zipAsBytes.Length);
fs.Close();
if (zipAsBytes.Length > 0)
{
_response.Status = "ZipFile";
_response.Result = base64String;
}
return _json.Serialize(_response);
This part of code returns the JSON data. This JSON data includes the Base64 string. Now what i want to do is to get the original zip file from Base64 string. I searched over the internet but not get the idea.
Is this achievable ?.
It is achievable. First you must convert the Base64 string to an Arraybuffer. Can be done with this function:
function base64ToBuffer(str){
str = window.atob(str); // creates a ASCII string
var buffer = new ArrayBuffer(str.length),
view = new Uint8Array(buffer);
for(var i = 0; i < str.length; i++){
view[i] = str.charCodeAt(i);
}
return buffer;
}
Then, using a library like JSZip, you can convert the ArrayBuffer to a Zip file and read its contents:
var buffer = base64ToBuffer(str);
var zip = new JSZip(buffer);
var fileContent = zip.file("someFileInZip.txt").asText();
JavaScript does not have that functionality.
Theoretically there can be some js library that does this, but it's size probably would be bigger than the original text file itself.
You can also enable gzip compression on your server, so that any output text gets compressed. Most of the browsers would then uncompress the data upon its arrival.

process cannot access the image file because it is being used by another process

i downloaded images from my deployed website and save it into my WPF app folder , basically i am running 2 platforms , a website and WPF . What i am trying to do is users uploaded their images using the web , so on the WPF side , i download the image from the web and display on my WPF app but i got this error :
The process cannot access the file
'C:\Users\apr13mpsipa\Desktop\OneOrganizer\OneOrganizer\bin\Debug\TaskImage\Fill
in the blanks.jpg' because it is being used by another process.
This is the code :
protected void DownloadData(string strFileUrlToDownload, string taskName)
{
WebClient client = new WebClient();
byte[] myDataBuffer = client.DownloadData(strFileUrlToDownload);
MemoryStream storeStream = new MemoryStream();
storeStream.SetLength(myDataBuffer.Length);
storeStream.Write(myDataBuffer, 0, (int)storeStream.Length);
storeStream.Flush();
currentpath = System.IO.Directory.GetCurrentDirectory() + #"\TaskImage\" + taskName + ".jpg"; //folder to contain files.
using (FileStream file = new FileStream(currentpath, FileMode.Create, System.IO.FileAccess.ReadWrite)) // ERROR HERE
{
byte[] bytes = new byte[storeStream.Length];
storeStream.Read(bytes, 0, (int)storeStream.Length);
file.Write(myDataBuffer, 0, (int)storeStream.Length);
storeStream.Close();
}
//The below Getstring method to get data in raw format and manipulate it as per requirement
string download = Encoding.ASCII.GetString(myDataBuffer);
}
I got the error when i try to display a image on a first button click , then i display the image again on the other button . basically this happens when i try to display the image 2 times.
---EDIT ------
Updated as of baldrick's comment :
DownloadData(fileUploadDirectory + daoTask.GetImage(aid, actTask.taskID).Substring(1), daoTask.GetTaskName(aid, actTask.taskID));
Image imgActivityTask = new Image();
imgActivityTask.Height = 90;
imgActivityTask.Width = 90;
imgActivityTask.Margin = new Thickness(10);
BitmapImage img = new BitmapImage();
img.BeginInit();
img.UriSource = new Uri(currentpath, UriKind.Absolute);
img.CreateOptions = BitmapCreateOptions.IgnoreImageCache;
img.EndInit();
imgActivityTask.Source = img;
Its still giving me the same error on the using line.
In you WPF code, you might need to specify the IgnoreImageCache setting:
yourImage.CacheOption = BitmapCacheOption.OnLoad;
yourImage.CreateOptions = BitmapCreateOptions.IgnoreImageCache
This might force it to load, and not lock the file.
The answer here deals with the same problem.
I am guessing you are leaving the file stream open.
Not sure why you are creating a memory stream (by the way, don't forget to close memory stream), and a file stream when you already have the bytes? Why not directly write to the file using File.WriteAllBytes?
WebClient client = new WebClient();
byte[] myDataBuffer = client.DownloadData(strFileUrlToDownload);
currentpath = System.IO.Directory.GetCurrentDirectory() + #"\TaskImage\" + taskName + ".jpg"; //folder to contain files.
File.WriteAllBytes(currentPath, myDataBuffer);
//The below Getstring method to get data in raw format and manipulate it as per requirement
string download = Encoding.ASCII.GetString(myDataBuffer);
Not sure why you are creating a memory stream (by the way, don't forget to close memory stream), and a file stream when you already have the bytes? Why not directly write to the file using File.WriteAllBytes?
WebClient client = new WebClient();
byte[] myDataBuffer = client.DownloadData(strFileUrlToDownload);
currentpath = System.IO.Directory.GetCurrentDirectory() + #"\TaskImage\" + taskName + ".jpg"; //folder to contain files.
File.WriteAllBytes(currentPath, myDataBuffer);
//The below Getstring method to get data in raw format and manipulate it as per requirement
string download = Encoding.ASCII.GetString(myDataBuffer);
Thanks

C# Save image without using Dialog

I am having trouble saving a user uploaded image to my "logos" file when the user presses "Save Team" on my form.
For you to get a taster of what the application does I have provided a screenshot here, upon pressing add team all the text box data is written to a text file and I want the image to automatically save into a predefined folder "logos", however I get the GDI++ error whenever I press save.
After reading through a few old threads on the web, I found that it could be caused by a few things such as file permissions, file size, the files name or even an open stream.
Below is the code I am currently using to save out my file which prompts the error:
private void btnAddTeam_Click(object sender, EventArgs e)
{
//VALIDATION FOR TEXT FILE AND OTHER STUFF HERE...
//SAVE THE IMAGE FILE
string filePath = picTeamLogo.ImageLocation;
Image tempImage = Image.FromFile(filePath);
tempImage.Save(#"../logos/");
}
If you are viewing the screenshot, please do not get confused by "arsenal.png" I am aware that that is not the full file path, its conversion is handled in another method, as only the filename is required to be written to the text file.
If anybody has any ideas on where I am going wrong then please point me in the right direction, vague errors such as the GDI one I just received are such a headache!
Alex.
Try this method
public void storeFile(FileUpload File, string dirName)
{
if (!Directory.Exists(MapPath("~/uploads/" + dirName)))
{
Directory.CreateDirectory(MapPath("~/uploads/" + dirName));
}
string saveLocation = MapPath("~/uploads/" + dirName + "/" + Path.GetFileName(File.FileName));
File.SaveAs(saveLocation);
}
that's because you have not specified the file name for save function !
take a look at this :
string filePath = picTeamLogo.ImageLocation;
FileInfo fi = new FileInfo(filePath);
Image tempImage = Image.FromFile(fi.FullName);
tempImage.Save(#"../logo/" + fi.Name);
now it works properly
See this earlier post of mine for similar issue...
A Generic error occurred in GDI+ in Bitmap.Save method
The stream remains locked - you can use memory stream as a temp location then save.
When either a Bitmap object or an Image object is constructed from a
file, the file remains locked for the lifetime of the object. As a
result, you cannot change an image and save it back to the same file
where it originated.
http://support.microsoft.com/?id=814675
string outputFileName = "...";
using (MemoryStream memory = new MemoryStream())
{
using (FileStream fs = new FileStream(outputFileName, FileMode.Create, FileAccess.ReadWrite))
{
tempImage.Save(memory, ImageFormat.Jpeg);
// memory.ToStream(fs) // I think the same
byte[] bytes = memory.ToArray();
fs.Write(bytes, 0, bytes.Length);
}
}
Or alternative is loading image via MemoryStream into the image - so the stream doesn't get locked in the first place...

Categories