Image/Jpeg Base 64 to Image - c#

I have image/jped base64 code like this,
data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQABAAD/2wBDAA......
I need, convert to image this code and save file as jpeg file. And I figured the Windows Form (C#). Insert to Textbox and button. Insert the base 64 code (the code is above) in textbox and click the button.
private void button1_Click(object sender, EventArgs e)
{
if (!string.IsNullOrEmpty(textBox1.Text))
{
string imageDataParsed = textBox1.Text.Substring(textBox1.Text.IndexOf(',') + 1);
byte[] imageBytes = Convert.FromBase64String(imageDataParsed);
MemoryStream ms1 = new MemoryStream(imageBytes);
Image img = Image.FromStream(ms1);
img.Save(Application.StartupPath + "\\Images\\1.jpg", ImageFormat.Jpeg);
}
}
File save as a jpeg. But this file seems like this on Windows Photo Viewer
But when I run on the Google Chrome this base 64 code, there is no problem. Viewing nice on Google Chrome browser.
Summary my question, I need base64 code to Image and save this file my server as jpeg file.
How can i solve this problem?
Thanks.

Convert Base64 straight to file avoid loading it into a Image, this way it should be all in-tact like the original image, of course this still doesn't solve your image showing problem.
byte[] newfile = Convert.FromBase64String(data);
File.WriteAllBytes(#"C:\path\to\file.jpg", newfile);

i think the problem is big endian and little endian mismatch see http://en.wikipedia.org/wiki/Endianness

Related

How can I get image content as pixel and create image from it in ASP.NET Core 6 Web API?

I try to save my images on my server, but I can't let my server save file and virus because of that I want to get image content as pixels of rgb and after that I create image by myself.
I can't use bitmap (or other type in C# like bitmapImage, ... etc) and I don't know how I can do this with sixlabors.ImageSharp.
I have some code that I tried but I can't implement the exact logic that I want (code shown here):
[HttpPost("[action]")]
public async Task<IActionResult> Get([FromForm] ImageFormat file)
{
await using var memoryStream = new MemoryStream();
await file.File.CopyToAsync(memoryStream);
IImageFormat format;
using (var image = Image.Load(memoryStream.ToArray(), out format))
{
using (var output = new MemoryStream())
{
image.Save(output, format);
var responseType = format.Name.ToLower();
return File(output.ToArray(), "application/octet-stream", file.File.FileName);
}
}
return null;
}
Can anybody help me with this problem?
i don't see a reason to convert image into image: there are several format zip-algorythms etc.wich you have to support in that case. example jpg is not bitmap, there is convertion issue - quality of image becomes less each conversion time. Image itself is not executable - it can be used only as container for virus body, can't harm your OSystem itself, another executable part should works somewhere.
But even if you would like to store images on disk, in other format - you can convert image to base64 text (one line of code, like example) - it less harmful and well known way to work with any file type. you can zip image by cszip, you can change file name and extension to hide file type.
I don't see a reasson to convert one image to another for this scenario/task.

How to display an image in an Asp:image?

So here's the deal, I have to take a text value from sql server, that beeing a encoded image, store it in a string and then I can convert it to Image type by decoding it, the thing is, how do I display said decoded image in the asp:image thing? cuz i whas hopping that this component would have an .image property where i can just put the image and it would display it just like that but it just has .ImageUrl that would work just fine if the image was stored in my pc but it isnĀ“t, I tried to make it a binary string and then instead of using and asp:image use img, then put the decoded image in .src by converting it to a base 64 string but i've been told that it only works with .jpg format and i have to use both .jpg and .png,
I'm new in asp.net so I may be making a dumb question but I search everywhere and I can't seem to find a clear solution, can somebody help me?
btw sorry if I'm barely understandable, English isn't my main language.
byte[] imageArray = System.IO.File.ReadAllBytes(Server.MapPath("~/App_Data/Images/client_group_logo.png"));
var imageString = imageArray != null ? Convert.ToBase64String(imageArray) : "";
var img = string.Format("data:image/jpg;base64,{0}", imageString);
ViewBag.ImagePath = img;
if you view this image.please paste this below code in your cshtml file.
<img src="#Url.Content(ViewBag.ImagePath)" />

PDFSharp compress filesize in c#

In my App i generate an PDF-File with PDFSharp.Xamarin which I got from this site:
https://github.com/roceh/PdfSharp.Xamarin
Everything is working fine.
In my PDF-Document I have many Images, which are compressed.
But the file size of my PDF-Document is too large.
Is there a possibility to compress my PDF-Document before saving it?
How can I work with the PdfSharp.SharpZipLib.Zip Namespace to deflate the file size?
UPDATE:
Here is my Code:
document = new PdfDocument();
document.Info.Title = nameDok.Replace(" ", "");
document.Info.Author = "---";
document.Info.CreationDate = DateTime.Now;
document.Info.Subject = nameDok.Replace(" ", "");
//That is how i add Images:
XImage image = XImage.FromStream(lstr);
gfx.DrawImage(image, 465, YPrev - 2, newimagewf, newimagehf);
document.CustomValues.CompressionMode = PdfCustomValueCompressionMode.Compressed;
document.Options.FlateEncodeMode = PdfFlateEncodeMode.BestCompression;
document.Save(speicherPfad);
Thanks for everyone.
I only know the original PDFsharp, not the Xamarin port: images are deflated automatically using SharpZipLib.
Make sure to use appropriate source images (e.g. JPEG or PNG, depending on the image).
On the project start page they write:
"Currently all images created via XGraphics are converted to jpegs with 70% quality."
This could mean that images are re-compressed, maybe leading to larger files than before.
Take one JPEG file, convert it to PDF, and check the size of the image (in bytes) in the PDF file.

base64 string image data is not completly displaying in ie8

I have to display an image,which is in base64 string format. It's working fine in ie9,chrome and mozilla.But when using ie8 image is not completly displaying.Due to security purpose i am not able save image on server and user url for displaying image.Is there any other way to display image on ie8.
As per the answer from Ryan McGrath at Internet Explorer and Base64 image display: IE8 can only show Base64 images up to 32KB in size.
Most likely your image is too large to be handled by IE8.
I don't have the time to write an extensive example right now, but a possible workaround would be to serve the image through another webpage. Read the image into a stream and send it back. For example, you might do something like this:
void GetImage(int imageId) {
byte[] imageData = GetDataFromDatabase(imageId);
using (MemoryStream ms = new MemoryStream(imageData)) {
Response.ContentType = "image/png";
ms.WriteTo(Response.OutputStream);
}
}
And then in your webpage you could do something like this:
<img src="Image.aspx?GetImage&imageId=1"/>
Note: All of the this is non-working code and possibly contains typos and non-existing methods. But it's just an idea to get you started. If you perform a Google search for "C# + asp.net output image" you get a whole bunch of results with working code samples, such as http://www.codeproject.com/Articles/33310/C-Save-and-Load-Image-from-Database.

Can't convert image to bytes[] C#

I'm very new to this stuff of saving images to the DB, and even when I thought it was very straight forward, it wasn't. What I'm trying to do is read and image file from the same computer in any format, display it in a picture box, and then convert the image to bytes to save it in the DB. Until now, I can display the image in the picture box, but I can't convert the image to bytes. Here's my code:
private void DisplayImage()
{
if (openFileDialog.ShowDialog(this) == DialogResult.OK)
{
try
{
Stream file;
if ((archivo = openFileDialog.OpenFile()) != null)
{
using (file)
{
pictureBox.Image = Image.FromStream(file);
}
}
}
catch (Exception ex)
{
...
}
}
}
That's a simple method that just displays the image in the picture box. The real problem is with the following method:
public static byte[] ConvertImageToBytes(Image image)
{
if (image != null)
{
MemoryStream ms = new MemoryStream();
using (ms)
{
image.Save(ms, ImageFormat.Bmp);
byte[] bytes = ms.ToArray();
return bytes;
}
}
else
{
return null;
}
}
When it tries to save the image to the memory stream, I get the error:
System.Runtime.InteropServices.ExternalException: A generic error occurred in GDI+.
Any ideas on what's happening?
You should use the RawFormat property of the original image as a parameter to the Save method, not default to a Bitmap. This will avoid image format type errors. eg:
image.Save(ms, image.RawFormat);
ms.Position = 0;
byte [] bytes=ms.ToArray();
I'd advise actually saving images to the file-system and simply storing the file path (preferably relative) in the database.
BLOBs (ie images etc) in a database cannot be indexed, are often stored in a secondary, slower access database area and will quickly blow out the size of the database (slower backups etc).
Cant you simply Read the file and load it to a byte[] using the File class:
byte[] imgData = System.IO.File.ReadAllBytes(#"C:\My Pic\Myfile.jpg");
You can pick the image path from your Open Dialog box.
That particular exception generally means that you are trying to save the image as the wrong format. In your code you specify ImageFormat.Bmp - is it actually a bitmap image, or did you perhaps load it from a JPEG or PNG? Attempting to save as a different format from the one you loaded will fail with ExternalException, as specified in the documentation.
Incidentally, I don't recommend storing images in a database and I believe most people here will agree. Databases may be able to handle this task but they are not optimized for it, and you end up hurting the performance of both your database and your application. Unless you are using SQL Server 2008 FILESTREAM columns, it is more efficient to store images on the file system.
It may be stupid to answer my own question, but I just found out that if I want to convert the Image object to bytes, I have to leave the original stream open. I saw this issue in another page I can't quite remember, and I tested it by leaving the stream open and it's true. So the format wasn't the problem. But I will take the advice of all of you and store the images in a separate directory. Thanks for your help guys!
The problem with this is that stream must be open during the lifetime of of the image otherwise will fail.
One solution that worked for me is just to create a copy of the image like this:
using (var ms = new MemoryStream(bytes))
{
_image = new Bitmap(Image.FromStream(ms));
}

Categories

Resources