I need to open a .png file as a string and put it in the textbox.I trying to do that by this code:
private void button1_Click(object sender, EventArgs e)
{
OpenFileDialog dialog = new OpenFileDialog();
dialog.ShowDialog();
text1.Text = dialog.FileName;
string text = System.IO.File.ReadAllText(dialog.FileName);
text2.Text = text;
}
I need to get in my multiline textbox something like this:
‰PNG
IHDR O Ů /ç%O sRGB ®Îé gAMA ±Źüa pHYs Ă ĂÇo¨d
(IDATx^íť˝ŽŢF˛†'T°łUčĐá *ô,°'Zl˛€®b7t8—0ˇB‡ľ'(;7Tb#p$ř«Ş9ŐĹźŻŮě˙®ŻŰ{H6«ş^5ÉŤžţ0ăÉÁŰĆ#,WXš*CĆxŰ0˛aEVv¶yۨ•ť&ˇÉŘ
oFU¬5Ńć$cĽm”ÂrĄIX:čëŢ6ęałĄ)26ŔŰFKŘĽbiÚŚ
đ¶a´yŰ…éJśť}ěí“/F×XŮŇ®čëŢŕŇÎFŘ”Ň}šäL/¶ľ=ń÷ĎƦ,ÎŇ$çuq¶Młan¦Ý4)3«MĂ0®ŇŠ”™Í؆‘ś:¦jŮŰM]Śa$${eŁŻx»y;5~yĆ›˛#§i±5ÂŰŇőĹωMY
·Ň„ľ^ŕmèU` ŇDĆxŰ0Ś®8´.;ŰĽml°Âčž3š?€6gĆ’p‚+’EîłŃ 6[«ŕ
but I get only one word:
�PNG
Please, help me!
Binary data are best read with the BinaryReader. To display them in a TextBox you need to replace the 0x00 character so it won't disrupt the Text in the control.
This will replace the 0x00 character by a '.' :
using (BinaryReader br = new BinaryReader(File.Open(yourFile, FileMode.Open)))
{
var data = br.ReadChars ((int)br.BaseStream.Length);
StringBuilder sb = new StringBuilder();
foreach (char c in data)
if ((int)c > 0) sb.Append(c.ToString()); else sb.Append(".");
text2.Text = sb.ToString();
}
Edit:
Your original code will also work if you modify the final assignment like this:
text2.Text = text.Replace((char)0, '.');
Explanation: In C# a string can hold arbitrary bit patterns; but the old Winform TextBox is still the same as way back before C#, probably written in C++ and will not handle the old string termination character 0x0 correctly.
While the original problem is not so much the use of File.ReadAllText, it is well worth having the BinaryReader with its many interesting methods in your toolbox..
And the result is not totally useless - I just found that my test file has an embedded Photoshop ICC profile ;-)
not sure why you are trying to do this, but If that's what you really want you can use base64 encoded string
Read a Image file:
Bitmap loadedBitmap = Bitmap.FromFile(dialog.Filename);
Image imgFile = Image.FromFile(dialog.Filename);
using (MemoryStream ms = new MemoryStream())
{
// Convert Image to byte[]
image.Save(ms, format);
byte[] imageBytes = ms.ToArray();
// Convert byte[] to Base64 String
string base64String = Convert.ToBase64String(imageBytes);
text2.Text = base64String;
}
and when you are reading that string back, you can do the reverse and convert base64 encoded string into an image....
Related
Image files are saved in base64 string format in the database.
I'm trying to load the image using DocuVieware via MemoryStream but failed.
Does anyone tried this kind of approach?
if (this.IsPostBack != true)
{
var file = new DataFileManager().GetImageByID(userID);
byte[] byt = System.Text.Encoding.UTF8.GetBytes(file.CurrentImage);
DocuVieware1.LoadFromStream(new MemoryStream(byt, 0, byt.Length), true);
}
You probably need to replace:
byte[] byt = System.Text.Encoding.UTF8.GetBytes(file.CurrentImage);
by:
byte[] data = Convert.FromBase64String(file.CurrentImage);
Ref: https://learn.microsoft.com/en-us/dotnet/api/system.convert.frombase64string?view=netframework-4.8
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);
}
I'm converting a binary file to text and dumping it into a PDF. I have this working, but I need to produce output that is identical to some samples of another program in a different language (it makes the text, then converts it to binary, so I guess I'm converting back?).
I get identical output except for one thing. I should have a bunch of dashes to set off subject headers, but instead I'm getting question marks (?). If I use Notepad++ to display the binary file, the question marks turn into some random Korean character (컴). I've tried doing result.Replace("?", "-"); and result.Replace("컴", "-"); and I've even tried checking with Contains(), but nothing is triggered.
How can I replace them?
Not sure if it will help, but here's my code:
private void btnConvertBinaryToPDF_Click(object sender, EventArgs e)
{
PdfDocument document = new PdfDocument(); //make new pdf document
PdfPage page = document.AddPage(); //add a page to the document
XGraphics gfx = XGraphics.FromPdfPage(page); //use this to draw/write on the specified page
XFont font = new XFont("Courier New", 10); //need a font to write with
string result = "";
string path = #"C:\Users\file";
byte[] b = new byte[1024];
UTF8Encoding temp = new UTF8Encoding(true);
FileStream fs = File.OpenRead(path);
int i = 1;
while (fs.Read(b, 0, b.Length) > 0)
{
string tmp = temp.GetString(b);
result += tmp;
b = new byte[1024]; //clear the buffer
}
if (result.Contains("?"))
{
Console.WriteLine("contains!");
}
result.Replace("컴", "-");
XTextFormatter tf = new XTextFormatter(gfx);
XRect rect = new XRect(40, 100, 500, 100);
tf.DrawString(result, font, XBrushes.Black, rect, XStringFormats.TopLeft);
string filename = "HelloWorld.pdf"; //make the filename
document.Save(filename); //save the document to the filename
Process.Start(filename); //open the file to show the document
}
EDIT: path contains binary data. I need to get the text representation of its contents. The above works fine, except in the case of ASCII characters numbered higher than 127.
It looks like you're simply making a mess of reading from the file. I'll assume that path contains text data; in which case, you might be better off simply using:
string result = File.ReadAllText(path);
optionally specifying an encoding:
string result = File.ReadAllText(path, Encoding.UTF8);
At the moment, you are:
treating more bytes as data than you read each iteration
not handling partial character reads
(there are also some inefficiencies in how you handle the string, the byte[] and the FileStream, but frankly that is moot if you're also getting the wrong answer)
Finally, your replace: does nothing:
result.Replace("컴", "-");
should be:
result = result.Replace("컴", "-");
(if it is still needed)
I would like to store the HTML 5 image src bytes into DB as binary or in a HardDisk. Later I want to read and assign it to img src="url"
Here is the HTML 5 code
<img src="data:image/gif;base64,R0lGODlhEAAOALMAAOazToeHh0tLS/7LZv/0jvb29t/
f3//Ub//ge8WSLf/rhf/3kdbW1mxsbP//mf///yH5BAAAAAAALAAAAAAQAA4AAARe8L1Ekyky67
QZ1hLnjM5UUde0ECwLJoExKcppV0aCcGCmTIHEIUEqjgaORCMxIC6e0CcguWw6aFjsVMkkIr7g7
7ZKPJjPZqIyd7sJAgVGoEGv2xsBxqNgYPj/gAwXEQA7" width="16" height="14" alt="embedded folder icon">
How do I parse this and store it as raw bytes or images into DB/File?
Note: The main reason for converting HTML 5 src bytes to DB/Harddisk image is, to generate the MS word 2007 format document which will embed those images.
How do I parse this
You can parse the data into a byte array using Convert.FromBase64String.
As to how to store the data in SQL, for such a small image, you might as well just store it in the base-64 encoded form. For larger images, you'll want to use a different method, but there are a myriad of answers there, and is probably better asked in a SQL forum.
private void button1_Click(object sender, EventArgs e)
{
// original source string
string src = #"data:image/gif;base64,R0lGODlhEAAOALMAAOazToeHh0tLS/7LZv/0jvb29t/ f3//Ub//ge8WSLf/rhf/3kdbW1mxsbP//mf///yH5BAAAAAAALAAAAAAQAA4AAARe8L1Ekyky67 QZ1hLnjM5UUde0ECwLJoExKcppV0aCcGCmTIHEIUEqjgaORCMxIC6e0CcguWw6aFjsVMkkIr7g7 7ZKPJjPZqIyd7sJAgVGoEGv2xsBxqNgYPj/gAwXEQA7";
// using regex replace to remove `data:image...` prefix
string pattern = #"data:image/(gif|png|jpeg|jpg);base64,";
string imgString = Regex.Replace(src, pattern, string.Empty);
byte[] imageBytes = Convert.FromBase64CharArray(imgString.ToCharArray(), 0, imgString.Length);
using (MemoryStream ms = new MemoryStream(imageBytes))
{
Image image = Image.FromStream(ms);
pictureBox1.Image = image;
}
// write to file
using(FileStream file = new FileStream("file.gif", FileMode.Create, FileAccess.Write))
{
file.Write(imageBytes, 0, imageBytes.Length);
}
}
and this is your image on form (just for example):
I am converting images to byte array and storing in a text file using the following code. I am retrieving them successfully as well.
My concern is that the quality of the retrieved image is not up to the expectation. Is there a way to have better conversion to byte array and retrieving? I am not worried about the space conception.
Please share your thoughts.
string plaintextStoringLocation = #"D:\ImageSource\Cha5.txt";
string bmpSourceLocation = #"D:\ImageSource\Cha50.bmp";
////Read image
Image sourceImg = Image.FromFile(bmpSourceLocation);
////Convert to Byte[]
byte[] clearByteArray = ImageToByteArray(sourceImg);
////Store it for future use (in plain text form)
StoreToLocation(clearByteArray, plaintextStoringLocation);
//Read from binary
byte[] retirevedImageBytes = ReadByteArrayFromFile(plaintextStoringLocation);
//Retrieve from Byte[]
Image destinationImg = ByteArrayToImage(retirevedImageBytes);
//Display Image
pictureBox1.Image = destinationImg;
EDIT: And the solution is - use Base64
//Plain Text Storing Location
string plaintextStoringLocation = #"D:\ImageSource\GirlInflower23.txt";
string bmpSourceLocation = #"D:\ImageSource\GirlInflower1.bmp";
////Read image
Image sourceImg = Image.FromFile(bmpSourceLocation);
string base64StringOfIMage = ImageToBase64(sourceImg, ImageFormat.Bmp);
byte[] byteOfString = Convert.FromBase64String(base64StringOfIMage);
StoreToLocation(byteOfString, plaintextStoringLocation);
byte[] retrievedBytesForStrimngForImage = ReadByteArrayFromFile(plaintextStoringLocation);
MemoryStream memStream = new MemoryStream(retrievedBytesForStrimngForImage);
//memStream.Read();
Image retrievedImg = Image.FromStream(memStream);
pictureBox1.Image = retrievedImg;
Yes, it is possible to get completely lossless storage. If you just store it in its original BMP format there will be no problem. I assume you are converting it to text because you want to send it via some protocol where binary characters will be corrupted.
Instead of whatever you are doing, you could consider using Convert.ToBase64String.
I haven't had any problems with this fragment...try it...if you get good results then the problem is in your Image -> byte[] or byte[] -> Image code :)
Image srcImage;
Image destImage;
// load an image
srcImage = Image.FromFile(filename);
// save the image via stream -> byte[]
using(MemoryStream stream = new MemoryStream()){
image.Save(stream, ImageFormat.xxx);
byte[] saveArray = stream.ToArray();
/*..... strore saveArray......*/
}
// rehydrate
byte[] loadArray = /*...get byte array from storage...*/
using(MemoryStream stream = new MemeoryStream(loadArray)){
destImage = Image.FromStream(stream);
}
pictureBox.Image = dstImage;
// don't forget...dispose of any Image/Stream objects