I want to save image in database - c#

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 .

Related

How to convert a base64 source to image source in xamarin

I want to convert a svg base64 string to image and need to assign that to image source in Xamarin How to implement the same . Please help on this.
Var dImage="data:image/avg+XML;base64,PD94b.....=="
My base64 string is in the above format.I did the normal base64 to image convertion but it didn't worked.
Can you please try it with plain data (without mime-type,...):
=> Convert.FromBase64String("PD94b.....==");
var dImage = "data:image/avg+XML;base64,PD94b.....==";
var base64 = dImage.Split(',')[1];
byte[] bytes = Convert.FromBase64String(base64);
Image image;
using (MemoryStream ms = new MemoryStream(bytes))
{
image = Image.FromStream(ms);
}

Image byte array is not saving properly

I want to save an image that exist in picture box as a byte array to the database.I am new to programming so please help me to resolve this. Everytime I save my image byte array in the database, it always shows the same byte array. 0x53797374656D2E427974655B5D but this is what I see always in the database. No matter which image I save, it will always saves this code: 0x53797374656D2E427974655B5D. Please help me to resolve this issue.
This is my code
Byte[] imgBytes = null;
ImageConverter imgConverter = new ImageConverter();
imgBytes =
(System.Byte[])imgConverter.ConvertTo(PictureBox1.Image,Type.GetType("System.Byte[]"));
To save an image, use Image.Save
ImageConverter is not for converting image to binary.
var stream = new MemoryStream();
PictureBox1.Image.Save(stream, ImageFormat.Png);
byte[] data = stream.ToArray();

Convert Html 5 img src data sting into Raw bytes or File

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):

How to convert Image to base64 format without Losing of Image Quality?

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.

C# - High Quality Byte Array Conversion of Images

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

Categories