I am converting Base64 code to image and I am using following way to save and display that image.
var kpin = Base64ToImage(TextBox1.Text);
kpin.Save(#"e:\myim.png");
Image1.ImageUrl = #"e:\myim.png";
and class is
public Image Base64ToImage(string base64String)
{
byte[] imageBytes = Convert.FromBase64String(base64String);
MemoryStream ms = new MemoryStream(imageBytes, 0,
imageBytes.Length);
ms.Write(imageBytes, 0, imageBytes.Length);
Image image = Image.FromStream(ms, true);
return image;
}
and this process working fine but I need an image not to be saved in hard disk. How to display this image directly without saving to hard disk and retrieving back.
Instead of setting the Image1.ImageURL to the path of your image, you can instead do one of several things:
Use an img tag with the Base64 data in it directly - http://www.sweeting.org/mark/blog/2005/07/12/base64-encoded-images-embedded-in-html
Not all browsers support this.
Create an Action or Webform (depending on whether you're using ASP.NET MVC or not) that takes as input whatever you need to either retrieve or generate the Base64 encoded data, and then set the response headers to serve the correct content type (image/png or something) and write the image directly to the Response.OutputStream (or use ContentResult in ASP.NET MVC). Tons of examples via Stackoverflow on how to do either.
-M
Don't bother with the image object at all, and just do it direct:
public void Base64ToResponse(string base64String)
{
Response.ContentType = "text/png"; //or whatever...
byte[] imageBytes = Convert.FromBase64String(base64String);
Response.OutputStream(imageBytes, 0, imageBytes.Length);
}
Related
HalconDotNet.HOperatorSet.ReadImage(out HObject image, srcPath);
//...
//(graphic stuff)
//...
HalconDotNet.HOperatorSet.WriteImage(imagePart, "png", 0, tmpImgPath); // skip these steps
Image = File.ReadAllBytes(path) // skip these steps
This piece of code is executed thousands of times. The last two steps are just there to have a compatibility step in between Halcon and .NET as I dont know how to combine them.
What I need is a way to convert a HImage(HObject) to a byte[], the same way WriteImage() + File.ReadAllBytes(path) would do. This last bit is important as this piece of code generates inputs for image classification models.
As the models are trained with data loaded from disk with File.ReadAllBytes(path) I'm assuming I need to prepare the data in the same way when using the model. When I read a 100x100 color PNG (solid color) with File.ReadAllBytes() I don't get 100x100x3 bytes, but 342, so I'm assuming the data is still compressed, and further assuming that I need to guarantee similar data when using the model.
This question has some overlap with this one but I need a byte[] instead of bitmap and just can't get it to work.
Can you try?
public static byte[] ImageToByte(Image image)
{
using (var stream = new MemoryStream())
{
image.Save(stream, System.Drawing.Imaging.ImageFormat.Png);
return stream.ToArray();
}
}
Or
Image image = Image.FromFile(imagePath);
byte[] byteArr = new byte[] { };
using (var ms = new MemoryStream())
{
image.Save(ms, image.RawFormat);
byteArr = ms.ToArray();
}
For Image you will need System.Drawing
From twitter direct message we get the media URL as "https://ton.twitter.com/1.1/ton/data/dm/xxxxxxxxxxxxxxxxxxxx/xxxxxxxxxxxxxxxxxxxxx/Mk2sMKio.png"
so to retrieve that image or show the image on the application we need to OAuth request which gives me Unicode data of the image. With the help of this https://www.phpclasses.org/blog/package/7700/post/9-Get-Twitter-Direct-Message-Images-in-PHP-with-the-OAuth-API.html
So now how to convert the Unicode data to Image in C#?
byte[] bytes = Encoding.Unicode.GetBytes(media);
string base64String = Convert.ToBase64String(bytes, 0, bytes.Length)
It converts to base64 as well but the image is not getting displayed shows an invalid image or blank. I had tried the same with different images
Try this.
byte[] imageBytes = Encoding.Unicode.GetBytes(media);
MemoryStream ms = new MemoryStream(imageBytes);
Image image = Image.FromStream(ms, true, true);
return image;
I have an image on a page, e.g <img id="img3" runat="server" src="image.jpg" width="200" height="200"/> and I'd like to save the image referenced by the src attribute in my database using stored procedure.
I should convert the image to binary first.
Here is what I have so far:
Stream fs = FileUpload1.PostedFile.InputStream;
BinaryReader br = new BinaryReader(fs);
Byte[] bytes = br.ReadBytes((Int32)fs.Length);
cmd.Parameters.AddWithValue("#img", byte);
But the thing is that I don't want to save the uploaded image FileUpload1.PostedFile.InputStream, I want to save the image that I had its src.
Is there a way to put the image src in stream so that I can save it or what is the right way for doing that?
Generally it is not recommended to store images in Database or any other type of files in RDBMS. What is most effective way, to store the file over disk on server, and store that path in your table.
So whenever you need to reference that image/file, then fetch the path from the database, and read the file from disk. This broadly has following two benefits.
Removes the extensive conversion process (from image to binary and
vice-versa).
Helps to read the image directly (soft-read).
Saving an image in the database is not recommanded, but if you insist on saving it in your database you can convert the image to base64, then save the base64 string in your database.
using (Image image = Image.FromStream(FileUpload1.PostedFile.InputStream))
{
using (MemoryStream m = new MemoryStream())
{
image.Save(m, image.RawFormat);
byte[] imageBytes = m.ToArray();
// Convert byte[] to Base64 String
string base64String = Convert.ToBase64String(imageBytes);
//Now save the base64String in your database
}
}
And to convert it back from base64 to an image:
public Image GetImageFromBase64String(string base64String)
{
byte[] bytes = Convert.FromBase64String(base64String);
Image image;
using (MemoryStream ms = new MemoryStream(bytes))
{
image = Image.FromStream(ms);
}
return image;
I combined some code from converting a base 64 string to an image and saving it
and from Convert image path to base64 string .
I would need to take a screenshot, if easy to without saving it. I would sent the image data directly to a PHP script. Because I don't have this PHP script at the moment, so I search for the easiest way of format in which I should convert the screenshot data. For debugging reasons until I've got my PHP script I would like to convert a picture of these data on my client side using C#.
My code at the moment for taking a screenshot and convert it (I'm not sure if I can convert the output in my logfile back into a picture):
internal static byte[] ImageToByteArray(Image img)
{
byte[] byteArray = new byte[0];
MemoryStream stream = new MemoryStream();
img.Save(stream, System.Drawing.Imaging.ImageFormat.Png);
stream.Close();
byteArray = stream.ToArray();
return byteArray;
}
public static string TakeScreenshot()
{
String filepath = #"C:\log2.txt";
Bitmap bitmap = new Bitmap(Screen.PrimaryScreen.Bounds.Width, Screen.PrimaryScreen.Bounds.Height, PixelFormat.Format32bppArgb);
Graphics graphics = Graphics.FromImage(bitmap);
graphics.CopyFromScreen(Screen.PrimaryScreen.Bounds.X, Screen.PrimaryScreen.Bounds.Y, 0, 0, Screen.PrimaryScreen.Bounds.Size, CopyPixelOperation.SourceCopy);
graphics.Dispose();
bitmap.Save("C:\\temp.png");
Image img = (Image)bitmap;
string str = System.Text.Encoding.Default.GetString(ImageToByteArray(img));
System.IO.File.AppendAllText(filepath, str);
//just for debugging
return "OH";
}
Main question at the moment, is there any way to get a picture back from my converted code (log2.txt).
This line of code:
string str = System.Text.Encoding.Default.GetString(ImageToByteArray(img));
Will almost certainly not do what you want it to do. It will try to interpret your byte array as a string in whatever is the default character encoding on your machine. If the default is something like UTF-8 or any multibyte character set, then it's quite likely to fail. Even if the default encoding is a single-byte character set, it could create a string that can't be reliably turned back into the original byte array.
If you really want to store the byte array as text, you can call Convert.ToBase64String:
string str = Convert.ToBase64String(ImageToByteArray(img));
If you read that string back from the file into str, you can rebuild the byte array with:
byte[] imageBytes = Convert.FromBase64String(str);
Another advantage in your particular case is that there are PHP functions for dealing with base 64 strings.
I have implemented two Winform Application,One application for Image to base64 Conversion and another for base64 string to Image Conversion.First i converted image to base64 string format.
Output of above application is base64 string.
for e.g code is
public string ImageToBase64(Image image, System.Drawing.Imaging.ImageFormat format)
{
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);
return base64String;
}
}
In my another application(base64 to Image conversion) i converted base64 string to image,the output of this application is image.
for e.g. code is
public Image Base64ToImage(string base64String)
{
// Convert Base64 String to byte[]
byte[] imageBytes = Convert.FromBase64String(base64String);
MemoryStream ms = new MemoryStream(imageBytes, 0, imageBytes.Length);
// Convert byte[] to Image
ms.Write(imageBytes, 0, imageBytes.Length);
Image image = Image.FromStream(ms, true);
return image;
}
The quality of this image is poor compare to previous image .how to resolve this?
The quality of this image is poor compare to previous image .how to resolve this?
Pass in an ImageFormat which doesn't lose quality, basically. This has nothing to do with the base64 encoding part - that's just a way of converting binary data to text and back. It's lossless.
To prove this to yourself, just save an image to a MemoryStream, rewind it and then load it from the stream - you'll see exactly the same loss of quality. Fix that, and the improvement will still be present when you use base64 to encode it as text.