C# Base64 String to Jpeg Image

converting a base 64 string to an image and saving it

Here is an example, you can modify the method to accept a string parameter. Then just save the image object with image.Save(...).

public Image LoadImage()
{
//data:image/gif;base64,
//this image is a single pixel (black)
byte[] bytes = Convert.FromBase64String("R0lGODlhAQABAIAAAAAAAAAAACH5BAAAAAAALAAAAAABAAEAAAICTAEAOw==");

Image image;
using (MemoryStream ms = new MemoryStream(bytes))
{
image = Image.FromStream(ms);
}

return image;
}

It is possible to get an exception A generic error occurred in GDI+. when the bytes represent a bitmap. If this is happening save the image before disposing the memory stream (while still inside the using statement).

C# Base64 String to JPEG Image

So with the code you have provided.

var bytes = Convert.FromBase64String(resizeImage.Content);
using (var imageFile = new FileStream(filePath, FileMode.Create))
{
imageFile.Write(bytes ,0, bytes.Length);
imageFile.Flush();
}

Convert base64 string to jpg/file

To keep it completely clean and simple, use something like this:

using (var img = new MemoryStream(bytes))
{
cloudBlockBlob.UploadFromStream(img);
}

This creates a MemoryStream that you can use to call CloudBlockBlob.UploadFromStream().

Edit
Or, like @mike-z said in the comment below, you can use CloudBlockBlob.UploadFromByteArray() directly.

Image from Base64 to Image

Hi Please find a version of working converters i had been using in the past,
Do tell if you need more explanation.

Seems like your conversion to base64 is the culprit!

       /// <summary>
///1 Convert String to Image
/// </summary>
/// <param name="commands"></param>
/// <returns></returns>

public Image ConvertStringtoImage(string commands)
{

byte[] photoarray = Convert.FromBase64String(commands);
MemoryStream ms = new MemoryStream(photoarray, 0, photoarray.Length);
ms.Write(photoarray, 0, photoarray.Length);
Image image = System.Drawing.Image.FromStream(ms);
return image;

}

/// <summary>
///2. Read picture from Database and return as image
/// just change the mysql to sql server type.
/// </summary>
/// <param name="commands"></param>
/// <returns></returns>

public Image Readphotofromdb(string commands)
{
Image image = null;
using (MySqlConnection dbConn = new MySqlConnection(connector))
{
using (MySqlCommand cmd = new MySqlCommand(commands, dbConn))
{
dbConn.Open();
using (MySqlDataReader reader = cmd.ExecuteReader())
{
if (reader.Read())
{
byte[] photoarray = Convert.FromBase64String(reader.GetString(0));
MemoryStream ms = new MemoryStream(photoarray, 0, photoarray.Length);
ms.Write(photoarray, 0, photoarray.Length);
image = new Bitmap(ms);

}
}
}
}
MySqlConnection.ClearAllPools();
return image;

}

/// <summary>
/// 3. Convert Image to base64 string
/// </summary>
/// <param name="image"></param>
/// <returns></returns>

public string ConvertImageToString(Image image)
{
byte[] byteArray = new byte[0];
using (MemoryStream stream = new MemoryStream())
{
image.Save(stream, System.Drawing.Imaging.ImageFormat.Png);
stream.Close();
byteArray = stream.ToArray();
}
string base64String = Convert.ToBase64String(byteArray);
return base64String;
}

c# Convert base64 to jpg image

In this line File.Copy(bytes.ToString()+".jpg", "\\\\192.168.2.9\\Web"); you are effectively trying to convert content of the bytes array and use it as an image name, but this will not actually create the file.

bytes.ToString() simply returns the type of the object not the content. That's why you are seeing System.Byte[].jpg

The way to solve the issue is to change your function:

protected void ExportToImage(object sender, EventArgs e)
{
string base64 = Request.Form[hfImageData.UniqueID].Split(',')[1];
byte[] bytes = Convert.FromBase64String(base64);
//write the bytes to file:
File.WriteAllBytes(@"c:\temp\somefile.jpg", bytes); //write to a temp location.
File.Copy(@"c:\temp\somefile.jpg", @"\\192.168.2.9\Web");//here we grab the file and copy it.
//EDIT: based on permissions you might be able to write directly to the share instead of a temp folder first.
}

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

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);
}

c# - base64 jpeg to MemoryStream?

The part at the start - data:image/jpeg;base64, - isn't part of the base64 data. So you need to remove that first:

const string Base64ImagePrefix = "data:image/jpeg;base64,"
...

if (user.FrontLicense.StartsWith(Base64ImagePrefix))
{
string base64 = user.FromLicense.Substring(Base64ImagePrefix.Length);
byte[] data = Convert.FromBase64String(base64);
// Use the data
}
else
{
// It didn't advertise itself as a base64 data image. What do you want to do?
}

Best way to separate base64 image from a string in C#

If there is an adequate HTML parser for this use case as suggested by others in the comments, go for that...

But, if that doesn't work, regular expressions to the rescue! This is using a positive lookbehind assertion and is matching everything until the first double quote. Should work -- adjust if it doesn't...

var val = "<p>This is test </p><p><img src=\"data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQABAAD/4gKgSUNDX1BST0ZJTEUA....+tzPaXLlstlSjpcxKPEqV/zH//2Q==";
var match = Regex.Match(val, "(?<=data:image/jpeg;base64,)[^\"]*");
Console.WriteLine(match.Value);

// output: /9j/4AAQSkZJRgABAQAAAQABAAD/4gKgSUNDX1BST0ZJTEUA....+tzPaXLlstlSjpcxKPEqV/zH//2Q==



Related Topics



Leave a reply



Submit