I have an image column in bytes in DB & location (which stores the path of the image),
if the path is empty i used image column, if the path is not empty, i load the image to a byte array and return the image as Memory stream either from file path or direct byte image column.
//query
select image,filepath from tablename;
byte[] Image = { };
if(file path is not empty)
{
System.Net.WebClient Client = new System.Net.WebClient();
Image = Client.DownloadData("Path of the image-http://....gif");
}
else
{
Image= datareader.GetOrdinal("image");
}
How do i assign a byte image to memory stream???
You can use the MemoryStream constructor that takes a byte[] instance:
byte[] data = // get data...
using (var stream = new MemoryStream(data))
{
}
If you already have an open stream, then just write the contents of the array:
stream.Write(data, 0, data.Length);
Related
//Retrieve an image in Jpg format and store it into a variable.
var imgFile = (ImageFile)ScanerItem.Transfer(FormatID.wiaFormatJPEG);
var Path = #"D:\ScanImg.jpg";
// save the image in some path with filename.
imgFile.SaveFile(Path);
pictureBox1.ImageLocation = Path;
Based on the following SO answer, you can get the byte[] of the image with (byte[])imgFile.FileData.get_BinaryData():
converting .__comobj WIA to byte[] in C# application
A bitmap can be put as source into the PictureBox.
Therefore the byte[] as to put into a MemoryStream and create a Bitmap:
var imgFile = (ImageFile)ScanerItem.Transfer(FormatID.wiaFormatJPEG);
byte[] imageBytes = (byte[])imgFile.FileData.get_BinaryData();
Bitmap image;
using (MemoryStream stream = new MemoryStream(imageBytes))
{
image = new Bitmap(stream);
}
pictureBox1.Image = image;
I am trying to store MemoryStream into MagicImage, but when I am trying to upload file with heic format it still uploading with heic format, but it should upload it with jpeg format. So I kind of do not understand where I am doing wrong. So could someone help me? I am trying it open in Frame in web, but it does not open bc it is not converting it to jpeg.
using (MemoryStream ms = new MemoryStream())
{
create.PostedFile.InputStream.CopyTo(ms);
var data = ms.ToArray();
byte[] data1 = null;
using (var image = new MagickImage(data))
{
// Sets the output format to jpeg
image.Format = MagickFormat.Jpeg;
// Create byte array that contains a jpeg file
data1 = image.ToByteArray();
}
var file = new ClientFile
{
Data = data1, // here where it should store it in jpeg
};
While I have never used your way of writing the image, this is what I use in my implementations and it always works:
var image = new MagickImage(sourceStream);
var format = MagickFormat.Jpg;
var stream = new MemoryStream();
image.Write(stream, format);
stream.Position = 0;
EDIT
If you don't add:
stream.Position = 0
sending the stream will not work as it will start saving from the current position which is at the end of the stream.
This question already has answers here:
Convert System.Windows.Media.ImageSource to ByteArray
(1 answer)
Convert byte array to image in wpf
(3 answers)
convert array of bytes to bitmapimage
(2 answers)
Closed 7 months ago.
Can anybody suggest how I can convert an image to a byte array and vice versa?
I'm developing a WPF application and using a stream reader.
Sample code to change an image into a byte array
public byte[] ImageToByteArray(System.Drawing.Image imageIn)
{
using (var ms = new MemoryStream())
{
imageIn.Save(ms,imageIn.RawFormat);
return ms.ToArray();
}
}
C# Image to Byte Array and Byte Array to Image Converter Class
For Converting an Image object to byte[] you can do as follows:
public static byte[] converterDemo(Image x)
{
ImageConverter _imageConverter = new ImageConverter();
byte[] xByte = (byte[])_imageConverter.ConvertTo(x, typeof(byte[]));
return xByte;
}
Another way to get Byte array from image path is
byte[] imgdata = System.IO.File.ReadAllBytes(HttpContext.Current.Server.MapPath(path));
Here's what I'm currently using. Some of the other techniques I've tried have been non-optimal because they changed the bit depth of the pixels (24-bit vs. 32-bit) or ignored the image's resolution (dpi).
// ImageConverter object used to convert byte arrays containing JPEG or PNG file images into
// Bitmap objects. This is static and only gets instantiated once.
private static readonly ImageConverter _imageConverter = new ImageConverter();
Image to byte array:
/// <summary>
/// Method to "convert" an Image object into a byte array, formatted in PNG file format, which
/// provides lossless compression. This can be used together with the GetImageFromByteArray()
/// method to provide a kind of serialization / deserialization.
/// </summary>
/// <param name="theImage">Image object, must be convertable to PNG format</param>
/// <returns>byte array image of a PNG file containing the image</returns>
public static byte[] CopyImageToByteArray(Image theImage)
{
using (MemoryStream memoryStream = new MemoryStream())
{
theImage.Save(memoryStream, ImageFormat.Png);
return memoryStream.ToArray();
}
}
Byte array to Image:
/// <summary>
/// Method that uses the ImageConverter object in .Net Framework to convert a byte array,
/// presumably containing a JPEG or PNG file image, into a Bitmap object, which can also be
/// used as an Image object.
/// </summary>
/// <param name="byteArray">byte array containing JPEG or PNG file image or similar</param>
/// <returns>Bitmap object if it works, else exception is thrown</returns>
public static Bitmap GetImageFromByteArray(byte[] byteArray)
{
Bitmap bm = (Bitmap)_imageConverter.ConvertFrom(byteArray);
if (bm != null && (bm.HorizontalResolution != (int)bm.HorizontalResolution ||
bm.VerticalResolution != (int)bm.VerticalResolution))
{
// Correct a strange glitch that has been observed in the test program when converting
// from a PNG file image created by CopyImageToByteArray() - the dpi value "drifts"
// slightly away from the nominal integer value
bm.SetResolution((int)(bm.HorizontalResolution + 0.5f),
(int)(bm.VerticalResolution + 0.5f));
}
return bm;
}
Edit: To get the Image from a jpg or png file you should read the file into a byte array using File.ReadAllBytes():
Bitmap newBitmap = GetImageFromByteArray(File.ReadAllBytes(fileName));
This avoids problems related to Bitmap wanting its source stream to be kept open, and some suggested workarounds to that problem that result in the source file being kept locked.
try this:
public byte[] imageToByteArray(System.Drawing.Image imageIn)
{
MemoryStream ms = new MemoryStream();
imageIn.Save(ms,System.Drawing.Imaging.ImageFormat.Gif);
return ms.ToArray();
}
public Image byteArrayToImage(byte[] byteArrayIn)
{
MemoryStream ms = new MemoryStream(byteArrayIn);
Image returnImage = Image.FromStream(ms);
return returnImage;
}
You can use File.ReadAllBytes() method to read any file into byte array. To write byte array into file, just use File.WriteAllBytes() method.
Hope this helps.
You can find more information and sample code here.
If you don't reference the imageBytes to carry bytes in the stream, the method won't return anything. Make sure you reference imageBytes = m.ToArray();
public static byte[] SerializeImage() {
MemoryStream m;
string PicPath = pathToImage";
byte[] imageBytes;
using (Image image = Image.FromFile(PicPath)) {
using ( m = new MemoryStream()) {
image.Save(m, image.RawFormat);
imageBytes = new byte[m.Length];
//Very Important
imageBytes = m.ToArray();
}//end using
}//end using
return imageBytes;
}//SerializeImage
Do you only want the pixels or the whole image (including headers) as an byte array?
For pixels: Use the CopyPixels method on Bitmap. Something like:
var bitmap = new BitmapImage(uri);
//Pixel array
byte[] pixels = new byte[width * height * 4]; //account for stride if necessary and whether the image is 32 bit, 16 bit etc.
bitmap.CopyPixels(..size, pixels, fullStride, 0);
Code:
using System.IO;
byte[] img = File.ReadAllBytes(openFileDialog1.FileName);
This is Code for converting the image of any type(for example PNG, JPG, JPEG) to byte array
public static byte[] imageConversion(string imageName){
//Initialize a file stream to read the image file
FileStream fs = new FileStream(imageName, FileMode.Open, FileAccess.Read);
//Initialize a byte array with size of stream
byte[] imgByteArr = new byte[fs.Length];
//Read data from the file stream and put into the byte array
fs.Read(imgByteArr, 0, Convert.ToInt32(fs.Length));
//Close a file stream
fs.Close();
return imageByteArr
}
To be convert the image to byte array.The code is give below.
public byte[] ImageToByteArray(System.Drawing.Image images)
{
using (var _memorystream = new MemoryStream())
{
images.Save(_memorystream ,images.RawFormat);
return _memorystream .ToArray();
}
}
To be convert the Byte array to Image.The code is given below.The code is handle A Generic error occurred in GDI+ in Image Save.
public void SaveImage(string base64String, string filepath)
{
// image convert to base64string is base64String
//File path is which path to save the image.
var bytess = Convert.FromBase64String(base64String);
using (var imageFile = new FileStream(filepath, FileMode.Create))
{
imageFile.Write(bytess, 0, bytess.Length);
imageFile.Flush();
}
}
This code retrieves first 100 rows from table in SQLSERVER 2012 and saves a picture per row as a file on local disk
public void SavePicture()
{
SqlConnection con = new SqlConnection("Data Source=localhost;Integrated security=true;database=databasename");
SqlDataAdapter da = new SqlDataAdapter("select top 100 [Name] ,[Picture] From tablename", con);
SqlCommandBuilder MyCB = new SqlCommandBuilder(da);
DataSet ds = new DataSet("tablename");
byte[] MyData = new byte[0];
da.Fill(ds, "tablename");
DataTable table = ds.Tables["tablename"];
for (int i = 0; i < table.Rows.Count;i++ )
{
DataRow myRow;
myRow = ds.Tables["tablename"].Rows[i];
MyData = (byte[])myRow["Picture"];
int ArraySize = new int();
ArraySize = MyData.GetUpperBound(0);
FileStream fs = new FileStream(#"C:\NewFolder\" + myRow["Name"].ToString() + ".jpg", FileMode.OpenOrCreate, FileAccess.Write);
fs.Write(MyData, 0, ArraySize);
fs.Close();
}
}
please note: Directory with NewFolder name should exist in C:\
This question already has answers here:
Convert System.Windows.Media.ImageSource to ByteArray
(1 answer)
Convert byte array to image in wpf
(3 answers)
convert array of bytes to bitmapimage
(2 answers)
Closed 7 months ago.
Can anybody suggest how I can convert an image to a byte array and vice versa?
I'm developing a WPF application and using a stream reader.
Sample code to change an image into a byte array
public byte[] ImageToByteArray(System.Drawing.Image imageIn)
{
using (var ms = new MemoryStream())
{
imageIn.Save(ms,imageIn.RawFormat);
return ms.ToArray();
}
}
C# Image to Byte Array and Byte Array to Image Converter Class
For Converting an Image object to byte[] you can do as follows:
public static byte[] converterDemo(Image x)
{
ImageConverter _imageConverter = new ImageConverter();
byte[] xByte = (byte[])_imageConverter.ConvertTo(x, typeof(byte[]));
return xByte;
}
Another way to get Byte array from image path is
byte[] imgdata = System.IO.File.ReadAllBytes(HttpContext.Current.Server.MapPath(path));
Here's what I'm currently using. Some of the other techniques I've tried have been non-optimal because they changed the bit depth of the pixels (24-bit vs. 32-bit) or ignored the image's resolution (dpi).
// ImageConverter object used to convert byte arrays containing JPEG or PNG file images into
// Bitmap objects. This is static and only gets instantiated once.
private static readonly ImageConverter _imageConverter = new ImageConverter();
Image to byte array:
/// <summary>
/// Method to "convert" an Image object into a byte array, formatted in PNG file format, which
/// provides lossless compression. This can be used together with the GetImageFromByteArray()
/// method to provide a kind of serialization / deserialization.
/// </summary>
/// <param name="theImage">Image object, must be convertable to PNG format</param>
/// <returns>byte array image of a PNG file containing the image</returns>
public static byte[] CopyImageToByteArray(Image theImage)
{
using (MemoryStream memoryStream = new MemoryStream())
{
theImage.Save(memoryStream, ImageFormat.Png);
return memoryStream.ToArray();
}
}
Byte array to Image:
/// <summary>
/// Method that uses the ImageConverter object in .Net Framework to convert a byte array,
/// presumably containing a JPEG or PNG file image, into a Bitmap object, which can also be
/// used as an Image object.
/// </summary>
/// <param name="byteArray">byte array containing JPEG or PNG file image or similar</param>
/// <returns>Bitmap object if it works, else exception is thrown</returns>
public static Bitmap GetImageFromByteArray(byte[] byteArray)
{
Bitmap bm = (Bitmap)_imageConverter.ConvertFrom(byteArray);
if (bm != null && (bm.HorizontalResolution != (int)bm.HorizontalResolution ||
bm.VerticalResolution != (int)bm.VerticalResolution))
{
// Correct a strange glitch that has been observed in the test program when converting
// from a PNG file image created by CopyImageToByteArray() - the dpi value "drifts"
// slightly away from the nominal integer value
bm.SetResolution((int)(bm.HorizontalResolution + 0.5f),
(int)(bm.VerticalResolution + 0.5f));
}
return bm;
}
Edit: To get the Image from a jpg or png file you should read the file into a byte array using File.ReadAllBytes():
Bitmap newBitmap = GetImageFromByteArray(File.ReadAllBytes(fileName));
This avoids problems related to Bitmap wanting its source stream to be kept open, and some suggested workarounds to that problem that result in the source file being kept locked.
try this:
public byte[] imageToByteArray(System.Drawing.Image imageIn)
{
MemoryStream ms = new MemoryStream();
imageIn.Save(ms,System.Drawing.Imaging.ImageFormat.Gif);
return ms.ToArray();
}
public Image byteArrayToImage(byte[] byteArrayIn)
{
MemoryStream ms = new MemoryStream(byteArrayIn);
Image returnImage = Image.FromStream(ms);
return returnImage;
}
You can use File.ReadAllBytes() method to read any file into byte array. To write byte array into file, just use File.WriteAllBytes() method.
Hope this helps.
You can find more information and sample code here.
If you don't reference the imageBytes to carry bytes in the stream, the method won't return anything. Make sure you reference imageBytes = m.ToArray();
public static byte[] SerializeImage() {
MemoryStream m;
string PicPath = pathToImage";
byte[] imageBytes;
using (Image image = Image.FromFile(PicPath)) {
using ( m = new MemoryStream()) {
image.Save(m, image.RawFormat);
imageBytes = new byte[m.Length];
//Very Important
imageBytes = m.ToArray();
}//end using
}//end using
return imageBytes;
}//SerializeImage
Do you only want the pixels or the whole image (including headers) as an byte array?
For pixels: Use the CopyPixels method on Bitmap. Something like:
var bitmap = new BitmapImage(uri);
//Pixel array
byte[] pixels = new byte[width * height * 4]; //account for stride if necessary and whether the image is 32 bit, 16 bit etc.
bitmap.CopyPixels(..size, pixels, fullStride, 0);
Code:
using System.IO;
byte[] img = File.ReadAllBytes(openFileDialog1.FileName);
This is Code for converting the image of any type(for example PNG, JPG, JPEG) to byte array
public static byte[] imageConversion(string imageName){
//Initialize a file stream to read the image file
FileStream fs = new FileStream(imageName, FileMode.Open, FileAccess.Read);
//Initialize a byte array with size of stream
byte[] imgByteArr = new byte[fs.Length];
//Read data from the file stream and put into the byte array
fs.Read(imgByteArr, 0, Convert.ToInt32(fs.Length));
//Close a file stream
fs.Close();
return imageByteArr
}
To be convert the image to byte array.The code is give below.
public byte[] ImageToByteArray(System.Drawing.Image images)
{
using (var _memorystream = new MemoryStream())
{
images.Save(_memorystream ,images.RawFormat);
return _memorystream .ToArray();
}
}
To be convert the Byte array to Image.The code is given below.The code is handle A Generic error occurred in GDI+ in Image Save.
public void SaveImage(string base64String, string filepath)
{
// image convert to base64string is base64String
//File path is which path to save the image.
var bytess = Convert.FromBase64String(base64String);
using (var imageFile = new FileStream(filepath, FileMode.Create))
{
imageFile.Write(bytess, 0, bytess.Length);
imageFile.Flush();
}
}
This code retrieves first 100 rows from table in SQLSERVER 2012 and saves a picture per row as a file on local disk
public void SavePicture()
{
SqlConnection con = new SqlConnection("Data Source=localhost;Integrated security=true;database=databasename");
SqlDataAdapter da = new SqlDataAdapter("select top 100 [Name] ,[Picture] From tablename", con);
SqlCommandBuilder MyCB = new SqlCommandBuilder(da);
DataSet ds = new DataSet("tablename");
byte[] MyData = new byte[0];
da.Fill(ds, "tablename");
DataTable table = ds.Tables["tablename"];
for (int i = 0; i < table.Rows.Count;i++ )
{
DataRow myRow;
myRow = ds.Tables["tablename"].Rows[i];
MyData = (byte[])myRow["Picture"];
int ArraySize = new int();
ArraySize = MyData.GetUpperBound(0);
FileStream fs = new FileStream(#"C:\NewFolder\" + myRow["Name"].ToString() + ".jpg", FileMode.OpenOrCreate, FileAccess.Write);
fs.Write(MyData, 0, ArraySize);
fs.Close();
}
}
please note: Directory with NewFolder name should exist in C:\
I am getting parameter is not valid error when trying to convert stream to image.
I my C# ASP.NET application, I upload an image to Amazon S3 and download it again for manipulation.
I've checked that the uploaded image is ok by viewing it online on S3.
I am downloading the image using this code:
using (AmazonS3 client = new AmazonS3Client(accessKey, secretKey))
{
GetObjectRequest request = new GetObjectRequest
{
BucketName = "mybucket",
Key = "temp/" + sp.FileGuid + Path.GetExtension(sp.FileName)
};
using (GetObjectResponse response = client.GetObject(request)) // S3Response
{
using (MemoryStream memStream = new MemoryStream())
{
int file_size_in_bytes = Convert.ToInt32(response.Headers.GetValues("Content-Length")[0]);
byte[] buffer = new Byte[file_size_in_bytes];
int numBytesToRead = file_size_in_bytes;
int read;
while ((read = response.ResponseStream.Read(buffer, 0, buffer.Length)) > 0)
{
memStream.Write(buffer, 0, read);
}
response.ResponseStream.Close();
...
I convert the response stream of the image to byte array in order to pass it to WCF service for later manipulation.
In the WCF I do (partial code):
using (Stream filestream = new MemoryStream(sp.ImageFile)
{
**// GET THE ERROR IN THIS LINE!**
System.Drawing.Image image = System.Drawing.Image.FromStream(filestream);
}
sp.ImageFile holds the convert response stream to byte array.
I read the byte array into a stream and create the image again from the stream. In the code above you can see where I get the parameter is not valid error.
I assume that in some place the conversion of the stream data of the image to either byte array or stream masses up the image data, so it created a corrupted image data, but I am not sure.
Spend all day trying to solve this without success. The only way it worked is when I directly pass the uploaded file stream to the System.Drawing.FromStream, but that's not what I want to do.
Really Need your help.
It's possible this may help. If the stream is not positioned at the begining the image may not load.
using (Stream filestream = new MemoryStream(sp.ImageFile)
{
var checkSeek = filestream.Seek(0, SeekOrigin.Begin);
**// GET THE ERROR IN THIS LINE!**
System.Drawing.Image image = System.Drawing.Image.FromStream(filestream);
}