Convert jpg string to image - c#

I have a jpg strign stored in "(string)HttpContext.Current.Session["image" + 0];" that I am trying to convert to a System.Drawing.Image.
I know the string is correct, because when I do this -
img.Src = "data:image/jpg;base64," + (string)HttpContext.Current.Session["image" + 0];
Everying works as intended.
But when I do this -
string inputString = (string)HttpContext.Current.Session["image" + 0];
byte[] imageBytes = Convert.FromBase64String(inputString);
using (MemoryStream ms = new MemoryStream(imageBytes))
{
System.Drawing.Image image = System.Drawing.Image.FromStream(ms, true);
}
I get and error telling me the format is incorrect when trying to create an image from the stream.
Please help

don't you need to convert webp to jpg/png first?
for example WebP-wrapper
using (WebP webp = new WebP())
{
var image = webp.Decode(imageBytes );
}

Related

How to convert PDF Base64 into pdf then PDF into an image in C#

following is the code added:
The image object is in the library.imaging.
"using System.Drawing;"
"using System.Drawing.Imaging;"
{
byte[] b = Convert.FromBase64String("R0lGODlhAQABAIAAA");
Image image;
using (MemoryStream memstr = new MemoryStream(b))
{
image = Image.FromStream(memstr);
}
}
Here is the new code I'm working on:
{
string base64BinaryStr = " ";
byte[] PDFDecoded = Convert.FromBase64String(base64BinaryStr);
string FileName = (#"C:\Users\Downloads\PDF " + DateTime.Now.ToString("dd-MM-yyyy-hh-mm"));
BinaryWriter writer = new BinaryWriter(File.Create(FileName + ".pdf"));
writer.Write(PDFDecoded);
string s = Encoding.UTF8.GetString(PDFDecoded);
}
So this is your current code:
byte[] PDFDecoded = Convert.FromBase64String(base64BinaryStr);
string FileName = (#"C:\Users\Downloads\PDF " + DateTime.Now.ToString("dd-MM-yyyy-hh-mm"));
BinaryWriter writer = new BinaryWriter(File.Create(FileName + ".pdf"));
writer.Write(PDFDecoded);
You don't actually need BinaryWriter for this. File.Create already gives you a FileStream:
FileStream writer = File.Create(FileName + ".pdf");
writer.Write(PDFDecoded, 0, PDFDecoded.Length);
But this will still have the problem you're experiencing because you're not flushing the data to it. We also need to close the file. Thankfully, we can wrap it in using and it will do both for us:
using (FileStream writer = File.Create(FileName + ".pdf"))
{
writer.Write(PDFDecoded, 0, PDFDecoded.Length);
}
But a simpler way to do this is:
File.WriteAllBytes(FileName + ".pdf", PDFDecoded);
As for PDF -> Image, you'll probably have to see if there is a library available for this (search "PDF to Image NuGet") that can help you with this as I don't think there is anything built-in.
Just a thought, you don't need to create a physical PDF file, you can have it in memory and convert it to image from there.
Now the problem is that you cannot use Image from System.Drawing.Imaging for this, it doesn't support reading PDF file.
Instead you'll need to search for some library that can do that.
For example, try GemBox.Pdf, you can use it like this:
string base64String = "...";
byte[] pdfBytes = Convert.FromBase64String(base64String);
using (PdfDocument pdfDocument = PdfDocument.Load(new MemoryStream(pdfBytes)))
{
ImageSaveOptions imageOptions = new ImageSaveOptions(ImageSaveFormat.Png);
string imageName = DateTime.Now.ToString("dd-MM-yyyy-hh-mm") + ".png";
pdfDocument.Save(#"C:\Users\Downloads\" + imageName, imageOptions);
}
I've used the code provided on this Convert example.

How to display image into picture box contain in string

I have an image string contain in an XML file and want to convert the string into an image. I have used the following code which is giving error: Parameter is not valid.
Code is following which is give above error:
Byte[] data = new Byte[0];
byte[] array = Encoding.ASCII.GetBytes("D:\notimg.txt");
MemoryStream mem = new MemoryStream(array);
pictureBox1.InitialImage = null;
pictureBox1.Image = Image.FromStream(mem);
Below is the data contained in XML tag which I need to convert into the image and display into picture box, I have placed the below data into a notepad file and removed the XML tag . Please, anyone, guide how to display the below data into an image. Thanks in advance.
<photograph>/9j/4AAQSkZJRgABAQECWAJYAAD/4QBuRXhpZgAATU0AKgAAAAgAAYdpAAQAAAABAAAAGgAAAAAAAZKGAAcAAAA6AAAALAAAAABVTklDT0RFAABDAHIAZQBhAHQAZQBkACAAYgB5ACAAQQBjAGMAdQBTAG8AZgB0ACAAQwBvAHIAcAAu/9sAQwAIBgYHBgUIBwcHCQkICgwUDQwLCwwZEhMPFB0aHx4dGhwcICQuJyAiLCMcHCg3KSwwMTQ0NB8nOT04MjwuMzQy/9sAQwEJCQkMCwwYDQ0YMiEcITIyMjIyMjIyMjIyMjIyMj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o2Fexna1qSWNpJIxG2PgDP3m7D8K8mvbvzJ5JnYu7nOSa0df1t9Um2odsMfTPc9ya52TG/nJrNa6krUa8vOf6Uwle/HvTWbsKYSTTGPLxjsW/HFAc5wFA96YBk+n1qTAUcc0gsOyxPapETPXg01flALbgPYU/wA4IRsBB9xmqDYRo2QZ2Fu9K0kQQgR4z69qYJJSSFC/yqMXbq3Qj2IyKWwD12gZ2kD+8vOKcueiPuBpquGOUOxsdu/4U/y2XGR15BFK4xsg5+dcEUi5Qe3oalXdnnml8vPNK4WIjjqBipFbB46U4Rd6csXQY5ouOwh42jtyRTgnzcdKVozwOmKkRe350XsFhwOUIPpTF4OAasqi46HNQSIQSF4+lCkKxLFICQA+D71bjlIPzZ+orMC4PuPep4d+OOcenWqFY6Kx1i4tCmx9yqcgZxiu+0fWIdTh+VgJUHzLXlCSEY7+xFX7DUJbOdZoppRRVDR//2Q==</photograph>
Quick and dirty:
var s = File.ReadAllText(#"d:\file.txt");
s = s.Replace("<photograph>", string.Empty).Replace("</photograph>", string.Empty);
var b = Convert.FromBase64String(s);
using (var mem = new MemoryStream(b))
{
pictureBox1.Image = Image.FromStream(mem);
}
It's Base64
first convert to byte[]
then use
public System.Drawing.Image Base64ToImage(byte[] imageBytes)
{
MemoryStream ms = new MemoryStream(imageBytes, 0, imageBytes.Length);
ms.Write(imageBytes, 0, imageBytes.Length);
System.Drawing.Image image = System.Drawing.Image.FromStream(ms, true);
return image;
}
then You Will Got image..!:)

How to convert Bitmap image to Base64PNG string in monodroid

Hi i want to convert bitmap image to base64png format i tried using the following code.i don't think the code works good enough.Any suggestions will be appreciated.
Bitmap immagex = signature;
MemoryStream baos = new MemoryStream();
immagex.Compress(Bitmap.CompressFormat.Png, 100, baos);
byte[] b = baos.ToArray();
String Base64Encodestring = Base64.EncodeToString(b, Base64.Default);
I belive this would do the trick.
string tempBase64 = Convert.ToBase64String(b);
Goodluck.

How to convert base64 string to image binary file and save onto server [duplicate]

This question already has answers here:
C# Base64 String to JPEG Image
(4 answers)
Closed 7 years ago.
As an example I have converted a canvas element with a re-sized image and posted into a hidden input field that's now encoded as
data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQABAAD...
This value then posted to the same page which I need to convert this string into an image and save onto the server.
Code Behind File (upload.aspx)
protected void btnUpload_Click(object sender, EventArgs e)
{
HttpPostedFile filePosted = Request.Files["newinput"];
string base64String = filePosted.ToString();
// 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);
System.Drawing.Image image = System.Drawing.Image.FromStream(ms, true);
//I DONT KNOW HOW TO WRITE ABOVE INTO THE SaveAs CONDITION BELOW
if (filePosted != null && filePosted.ContentLength > 0)
{
string fileNameApplication = Path.GetFileName(filePosted.FileName);
string fileExtensionApplication = Path.GetExtension(fileNameApplication);
// generating a random guid for a new file at server for the uploaded file
string newFile = Guid.NewGuid().ToString() + fileExtensionApplication;
// getting a valid server path to save
string filePath = Path.Combine(Server.MapPath("~/Assets/") + Request.QueryString["id"] + "/", newFile);
if (fileNameApplication != String.Empty)
{
filePosted.SaveAs(filePath);
}
}
I'm pretty sure I need to convert this the imagedata to a binary file before saving on the server but I can't quite get how I need to amend the code above. Any ideas? The code to save to the server doesn't work.
Once I have converted this to an image and changed it's name as above - I'm storing this back to a database via LINQ - with a URL appended to it.
Any help would be greatly appreciated.
Hope below functions helps.
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;
}
}
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;
}
EDIT 1 -
From the comments it seems that you are getting base64 string and you need to save it as image on server and then whenever required you need to show that image using physical server path.
Ok. Base64ToImage will give you image for your base64 string. You can save it on server using
image.Save("PATH", System.Drawing.Imaging.ImageFormat.Jpeg);
And this "PATH" you have supplied or created can be stored in DB as URL, which you can use at the time of display.
Note: Make sure that you have write access to folder where you are saving image.
EDIT-2
Your function should look like below. Please put validation code, error handling as required.
protected void btnUpload_Click(object sender, EventArgs e)
{
HttpPostedFile filePosted = Request.Files["newinput"];
string base64String = filePosted.ToString();
// 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);
System.Drawing.Image image = System.Drawing.Image.FromStream(ms, true);
string newFile = Guid.NewGuid().ToString() + fileExtensionApplication;
string filePath = Path.Combine(Server.MapPath("~/Assets/") + Request.QueryString["id"] + "/", newFile);
image.Save(filepath,ImageFormat.Jpeg);
}

Convert ImageSource to Base64String - WP8

am working on WP8application, I have few images in location Resources\Graphics\ i am trying to display images from these folder, but its not picking the path.
Here is my code :
<img src=\"/Resources;component/Graphics/"+ImageName).Append("\" ") this is in my string which i am using in my WebBrowserControl.
WebBrowserControl.NavigateToString(html); // here html is a string which has all the html code in it.
But its not display the images.
So i want to convert the ImageSource --Resources;component/Graphics/"+ImageName to Base64String how to do it?
I have looked into many examples but none of them is compatible for WP8.
You can get StreamInfo by using this:
Application.GetResourceStream(new Uri("Resources;component/Graphics/"+ImageName", System.UriKind.Relative));
Then you can read this stream into an byte array. After that, use Convert.ToBase64String() to get what you want. Try this. Maybe you can read the MSDN document to find how to use Stream.
var img = Application.GetResourceStream(new Uri("Resources;component/Graphics/"+ImageName", System.UriKind.Relative));
var buffer = new byte[img.Stream.Length];
img.Stream.Seek(0, SeekOrigin.Begin);
img.Stream.Read(buffer, 0, buffer.Length);
var base64 = Convert.ToBase64String(buffer);
It's very simple - load your image into a byte array and call
System.Convert.ToBase64String(imageArray).
That being said, this will not result in displaying the image. The NavigateToString requires html. See documentation
This is my code
byte[] bytearray = null;
using (var ms = new MemoryStream())
{
if (bmp != null)
{
var wbitmp = new WriteableBitmap(bmp);
wbitmp.SaveJpeg(ms, 46, 38, 0, 100);
bytearray = ms.ToArray();
}
}
if (bytearray != null)
{
// image base64 here
string btmStr = Convert.ToBase64String(bytearray);
}

Categories