I used
private BitmapImage byteArrayToImage(byte[] byteArrayIn)
{
try
{
MemoryStream stream = new MemoryStream();
stream.Write(byteArrayIn, 0, byteArrayIn.Length);
stream.Position = 0;
System.Drawing.Image img = System.Drawing.Image.FromStream(stream);
BitmapImage returnImage = new BitmapImage();
returnImage.BeginInit();
MemoryStream ms = new MemoryStream();
img.Save(ms, System.Drawing.Imaging.ImageFormat.Bmp);
ms.Seek(0, SeekOrigin.Begin);
returnImage.StreamSource = ms;
returnImage.EndInit();
return returnImage;
}
catch (Exception ex)
{
throw ex;
}
return null;
}
This method in my application to convert byte array to an image. But it throws "Parameter is not valid" exception.. why it is happening..? Is there any alternative method.??
Hi this should be working:
private static BitmapImage LoadImage(byte[] imageData)
{
if (imageData == null || imageData.Length == 0) return null;
var image = new BitmapImage();
using (var mem = new MemoryStream(imageData))
{
mem.Position = 0;
image.BeginInit();
image.CreateOptions = BitmapCreateOptions.PreservePixelFormat;
image.CacheOption = BitmapCacheOption.OnLoad;
image.UriSource = null;
image.StreamSource = mem;
image.EndInit();
}
image.Freeze();
return image;
}
If you have array like this:
byte[] byteArrayIn = new byte[] {255, 128, 0, 200};
And you want something like:
Use:
BitmapSource bitmapSource = BitmapSource.Create(2, 2, 300, 300,PixelFormats.Indexed8, BitmapPalettes.Gray256, byteArrayIn, 2);
Image.Source = bitmapSource;
In xaml:
<Image RenderOptions.BitmapScalingMode="NearestNeighbor" RenderOptions.EdgeMode="Aliased" x:Name="Image"></Image>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private void btnBrowse_Click(object sender, RoutedEventArgs e)
{
var of = new OpenFileDialog();
of.Filter = "Image files (*.png;*.jpeg)|*.png;*.jpeg|All files (*.*)|*.*";
var res = of.ShowDialog();
if (res.HasValue)
{
imgPreview.Source = new BitmapImage(new Uri(of.FileName));
var t = Utils.ConvertBitmapSourceToByteArray(imgPreview.Source as BitmapSource);
var d = Utils.ConvertBitmapSourceToByteArray(new BitmapImage(new Uri(of.FileName)));
var s = Utils.ConvertBitmapSourceToByteArray(imgPreview.Source);
var enc = Utils.ConvertBitmapSourceToByteArray(new PngBitmapEncoder(), imgPreview.Source);
//imgPreview2.Source = Utils.ConvertByteArrayToBitmapImage(enc);
imgPreview2.Source = Utils.ConvertByteArrayToBitmapImage2(enc);
//var i = 0;
}
else
{
MessageBox.Show("Select a currect file...");
}
}
}
/util.cs/
public class Utils
{
public static byte[] ConvertBitmapSourceToByteArray(BitmapEncoder encoder, ImageSource imageSource)
{
byte[] bytes = null;
var bitmapSource = imageSource as BitmapSource;
if (bitmapSource != null)
{
encoder.Frames.Add(BitmapFrame.Create(bitmapSource));
using (var stream = new MemoryStream())
{
encoder.Save(stream);
bytes = stream.ToArray();
}
}
return bytes;
}
public static byte[] ConvertBitmapSourceToByteArray(BitmapSource image)
{
byte[] data;
BitmapEncoder encoder = new JpegBitmapEncoder();
encoder.Frames.Add(BitmapFrame.Create(image));
using (MemoryStream ms = new MemoryStream())
{
encoder.Save(ms);
data = ms.ToArray();
}
return data;
}
public static byte[] ConvertBitmapSourceToByteArray(ImageSource imageSource)
{
var image = imageSource as BitmapSource;
byte[] data;
BitmapEncoder encoder = new JpegBitmapEncoder();
encoder.Frames.Add(BitmapFrame.Create(image));
using (MemoryStream ms = new MemoryStream())
{
encoder.Save(ms);
data = ms.ToArray();
}
return data;
}
public static byte[] ConvertBitmapSourceToByteArray(Uri uri)
{
var image = new BitmapImage(uri);
byte[] data;
BitmapEncoder encoder = new JpegBitmapEncoder();
encoder.Frames.Add(BitmapFrame.Create(image));
using (MemoryStream ms = new MemoryStream())
{
encoder.Save(ms);
data = ms.ToArray();
}
return data;
}
public static byte[] ConvertBitmapSourceToByteArray(string filepath)
{
var image = new BitmapImage(new Uri(filepath));
byte[] data;
BitmapEncoder encoder = new JpegBitmapEncoder();
encoder.Frames.Add(BitmapFrame.Create(image));
using (MemoryStream ms = new MemoryStream())
{
encoder.Save(ms);
data = ms.ToArray();
}
return data;
}
public static BitmapImage ConvertByteArrayToBitmapImage(Byte[] bytes)
{
var stream = new MemoryStream(bytes);
stream.Seek(0, SeekOrigin.Begin);
var image = new BitmapImage();
image.BeginInit();
image.StreamSource = stream;
image.EndInit();
return image;
}
}
Related
I have converted image byte array into hexastring using following snippet:
public static string ByteArrayToHexString(byte[] byteArray)
{
if (byteArray == null)
return string.Empty;
try
{
StringBuilder sb = new StringBuilder();
for (int i = 0; i < byteArray.Length; i++)
{
sb.Append(byteArray[i].ToString("X2"));
}
return sb.ToString();
}
catch
{
throw;
}
}
While converting back hexastring into WriteableBitmap using following code getting error:
public static WriteableBitmap GetImage(byte[] rawImageBytes)
{
WriteableBitmap image;
using (MemoryStream ms = new MemoryStream(rawImageBytes))
{
//create decoder from MemoryStream
BitmapDecoder decoder = BitmapDecoder.Create(ms,
BitmapCreateOptions.PreservePixelFormat,
BitmapCacheOption.OnLoad);
//create new bitmap that is detached from the MemoryStream
image = new WriteableBitmap(decoder.Frames[0]);
image.Freeze();
return image;
}
}
error
I want to add an image to the database in an image column in byte form
I am using SQLite to save my database data and WPF Application using dbContext c# to write my code
can anyone help me please?
private void ChooseImageButtonClick(object sender, RoutedEventArgs e)
{
Microsoft.Win32.OpenFileDialog dlg = new Microsoft.Win32.OpenFileDialog();
dlg.Filter = "Choose Image(*.JPG;*.PNG;*.GIF)|*.jpg;*.png;*.gif";
if (dlg.ShowDialog() == true)
{
string FileName = dlg.FileName.ToString();
BitmapImage bitmap = new BitmapImage();
bitmap.BeginInit();
bitmap.UriSource = new Uri(FileName);
bitmap.EndInit();
ImageBox.Source = bitmap;
}
}
private void savebtnClick(object sender, RoutedEventArgs e)
{
using (DatabaseContext dbContext = new DatabaseContext())
{
Person p = new Person
{
Id = int.Parse(Idtextbox.Text),
Name = Nametextbox.Text,
Image = image
};
dbContext.Person.Add(p);
dbContext.SaveChanges();
RefreshList();
}
}
Just convert BitmapImage to byte array first
byte[] image;
JpegBitmapEncoder encoder = new JpegBitmapEncoder();
encoder.QualityLevel = 100;
using (MemoryStream ms = new MemoryStream())
{
encoder.Frames.Add(BitmapFrame.Create((BitmapSource)ImageBox.Source));
encoder.Save(ms);
image = ms.ToArray();
}
encoder = null;
And in your database context - add
using (DatabaseContext dbContext = new DatabaseContext())
{
Part part = new Part();
part.Id = int.Parse(TextBoxID.Text);
part.Name = TextBoxName.Text;
part.Image = image;
dbContext.Part.Add(part);
dbContext.SaveChanges();
RefreshPartsList();
}}
To convert byte array back to BitmapImage :
byte[] imageData = part.Image; // that you get from db
if (imageData == null || imageData.Length == 0)
{
//Show error msg or return here;
return;
}
var image = new BitmapImage();
using (var ms = new System.IO.MemoryStream(imageData))
{
image.BeginInit();
image.CacheOption = BitmapCacheOption.OnLoad;
image.StreamSource = ms;
image.EndInit();
image.Freeze();
}
Add Property in 'Part' class
public byte[] ImageCol { get; set; }
Then from "OpenFileDialog" create Image from selected file. For Example
OpenFileDialog openFileDialog = new OpenFileDialog
{
Filter = "Image Files(*.BMP;*.JPG;*.JPEG;*.GIF;*.PNG)|*.BMP;*.JPG;*.JPEG;*.GIF;*.PNG",
InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments)
};
if (openFileDialog.ShowDialog()==DialogResult.OK)
{
var imageFromFile = System.Drawing.Image.FromFile(openFileDialog.FileName);
part.ImageCol = imageFromFile.ConvertBitmapImagetoBytes();
}
Convert BitMap to byte[]
public static byte[] ConvertBitmapImagetoBytes(this Image image)
{
MemoryStream ms = new MemoryStream();
image.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
return ms.ToArray();
}
I need to convert a BitmapImage in a byte[] but I don't find how to do it in C# web.
I found examples but none of them work (JpegBitmapEncoder doesn't exist, BitmapImageObject.StreamSource doesn't exist, there isn't WriteableBitmap constructor with BitmapImage as parameter, Extensions.SaveJpeg(parameters) doesn't exist ...).
Examples I found:
Constructor new WriteableBitmap(bitmapImage) doesn't exist.
public static byte[] ConvertToBytes(this BitmapImage bitmapImage)
{
byte[] data;
// Get an Image Stream
using (MemoryStream ms = new MemoryStream())
{
WriteableBitmap btmMap = new WriteableBitmap(bitmapImage);
// write an image into the stream
Extensions.SaveJpeg(btmMap, ms,
bitmapImage.PixelWidth, bitmapImage.PixelHeight, 0, 100);
// reset the stream pointer to the beginning
ms.Seek(0, 0);
//read the stream into a byte array
data = new byte[ms.Length];
ms.Read(data, 0, data.Length);
}
//data now holds the bytes of the image
return data;
}
new WriteableBitmap(img), System.Windows.Media.Imaging.Extensions.SaveJpeg don't exist.
public static byte[] ImageToBytes(BitmapImage img)
{
using (MemoryStream ms = new MemoryStream())
{
WriteableBitmap btmMap = new WriteableBitmap(img);
System.Windows.Media.Imaging.Extensions.SaveJpeg(btmMap, ms, img.PixelWidth, img.PixelHeight, 0, 100);
img = null;
return ms.ToArray();
}
}
imageSource.StreamSource doesn't exist.
public static byte[] ImageToByte(BitmapImage imageSource)
{
Stream stream = imageSource.StreamSource;
Byte[] buffer = null;
if (stream != null && stream.Length > 0)
{
using (BinaryReader br = new BinaryReader(stream))
{
buffer = br.ReadBytes((Int32)stream.Length);
}
}
return buffer;
}
JpegBitmapEncoder doesn't exist.
byte[] data;
JpegBitmapEncoder encoder = new JpegBitmapEncoder();
encoder.Frames.Add(BitmapFrame.Create(bitmapImage));
using(MemoryStream ms = new MemoryStream())
{
encoder.Save(ms);
data = ms.ToArray();
}
Try with the using statement to a namespace in the beginning of your code.
Otherwise there should be some Nuget packages which you could install to achieve your goal.
using System.Drawing;
In Main method
Image img = Image.FromFile("path to the file");
var byteArray = ImageToByte(img);
public static byte[] ImageToByte(Image img)
{
ImageConverter converter = new ImageConverter();
return (byte[])converter.ConvertTo(img, typeof(byte[]));
}
Try this
I think this will help...
public byte[] ConvertBitMapToByteArray(Bitmap bitmap)
{
byte[] result = null;
if (bitmap != null)
{
MemoryStream stream = new MemoryStream();
bitmap.Save(stream, bitmap.RawFormat);
result = stream.ToArray();
}
return result;
}
byte[] foo = System.IO.File.ReadAllBytes("bitmap path");
Or
byte[] foo;
Object obj = YourBitmap;
BinaryFormatter bf = new BinaryFormatter();
using (var ms = new MemoryStream())
{
bf.Serialize(ms, obj);
foo = ms.ToArray();
}
Or
ImageConverter foocon = new ImageConverter();
byte[] foo = (byte[])foocon.ConvertTo(YourBitmap, typeof(byte[]));
Or
MemoryStream ms = new MemoryStream();
Bitmap.Save(ms, YourBitmap.RawFormat);
byte[] foo = ms.ToArray();
Finally, it seems that, obviously, it missed some libraries but we are limited with our application, so we decided to recover our pictures by another way. Anyway, thank you all.
I have jpeg.
I convert it to a BitmapImage.
I then reduce the quality (compression).
I then covert to byte array.
I have found the memory escalates very quickly in task manager.
I am certain I am disposing all that I can.
This is my code:
//I am calling this from within a timer set 500ms
byte[] datatest = JpegXr.SaveJpegXrToBytes((Bitmap)frame.Clone(), 40f);
frame.Dispose();
public static class JpegXr
{
public static Bitmap BitmapImage2Bitmap(BitmapImage bitmapImage)
{
// BitmapImage bitmapImage = new BitmapImage(new Uri("../Images/test.png", UriKind.Relative));
using (MemoryStream outStream = new MemoryStream())
{
BitmapEncoder enc = new BmpBitmapEncoder();
enc.Frames.Add(BitmapFrame.Create(bitmapImage));
enc.Save(outStream);
System.Drawing.Bitmap bitmap = new System.Drawing.Bitmap(outStream);
// return bitmap; <-- leads to problems, stream is closed/closing ...
return new Bitmap(bitmap);
}
}
public static byte[] SaveJpegXrToBytes(Bitmap bitmap, float quality)
{
byte[] data = null;
var stream = new MemoryStream();
SaveJpegXr(bitmap, quality, stream);
stream.Seek(0, SeekOrigin.Begin);
data= stream.ToArray();
stream.Close();
bitmap.Dispose();
return data;
}
private static BitmapImage Bitmap2BitmapImage(Bitmap bitmap)
{
BitmapSource bitmapSource = Imaging.CreateBitmapSourceFromHBitmap(
bitmap.GetHbitmap(),
IntPtr.Zero, System.Windows.Int32Rect.Empty,
BitmapSizeOptions.FromEmptyOptions());
//BitmapSource bitmapSource = Clipboard.GetImage();
JpegBitmapEncoder encoder = new JpegBitmapEncoder();
MemoryStream memoryStream = new MemoryStream();
BitmapImage bImg = new BitmapImage();
encoder.Frames.Add(BitmapFrame.Create(bitmapSource));
encoder.Save(memoryStream);
bImg.BeginInit();
bImg.StreamSource = new MemoryStream(memoryStream.ToArray());
bImg.EndInit();
memoryStream.Close();
bitmap.Dispose();
return bImg;
//return (BitmapImage)i;
//return i;
}
private static void SaveJpegXr(Bitmap bitmap, float quality, Stream output)
{
BitmapImage bitmapSource = Bitmap2BitmapImage((Bitmap)bitmap.Clone());
//var bitmapSource = bitmap.ToWpfBitmap();
var bitmapFrame = BitmapFrame.Create(bitmapSource);
var jpegXrEncoder = new WmpBitmapEncoder();
jpegXrEncoder.Frames.Add(bitmapFrame);
jpegXrEncoder.ImageQualityLevel = quality / 100f;
jpegXrEncoder.Save(output);
bitmap.Dispose();
}
}
Is it just the case that doing these conversions is memory consuming by its very nature and as such calling it frequently from within a timer does not give the garbage collector time to dispose objects correctly?
Appreciate peoples wisdom on this...
The image is meant to be added to an update sql statement to update the image id a user changes the picture. I am trying to call the displayPhoto method into the savebtn method and assign it to residentImage variable as the image placeholder.
PhotoDisplay Method:
private void DisplayPhoto(byte[] photo)
{
if (!(photo == null))
{
MemoryStream stream = new MemoryStream();
stream.Write(photo, 0, photo.Length);
stream.Position = 0;
System.Drawing.Image image = System.Drawing.Image.FromStream(stream);
BitmapImage bitmapImage = new BitmapImage();
bitmapImage.BeginInit();
MemoryStream memoryStream = new MemoryStream();
image.Save(memoryStream, System.Drawing.Imaging.ImageFormat.Bmp);
memoryStream.Seek(0, SeekOrigin.Begin);
bitmapImage.StreamSource = memoryStream;
bitmapImage.EndInit();
ResidentImage.Source = bitmapImage;
ResidentProfileImage.Source = bitmapImage;
}
else
{
ResidentImage.Source = new BitmapImage(new Uri("pack://application:,,,/Resources/ResidentImage.jpg"));
}
}
Save Button Method:
private void btnSave_Click(object sender, RoutedEventArgs e)
{
Resident hello = new Resident();
hello.Doctor = new Doctor();
hello.Room = new Room();
hello.addtionalInformation = txtAdditionalInformation.Text;
hello.FirstName = txtForename.Text;
hello.Surname = txtSurname.Text;
hello.Title = txtTitle.Text;
hello.ResidentID = GlobalVariables.SelectedResident.ResidentID;
hello.Doctor.DoctorID = GlobalVariables.SelectedResident.Doctor.DoctorID;
hello.Room.RoomID= GlobalVariables.SelectedResident.Room.RoomID;
hello.Room.Name = txtRoomNo.Text;
hello.Allergies = txtResidentAlergies.Text;
hello.Photo = DisplayPhoto(hello.Photo);
hello.DateOfBirth = DateTime.Parse(txtDOB.Text);
ResidentData.Update(hello);
}
You have defined your DisplayPhoto function to be a 'void' function, meaning that it returns nothing.
Then how do you expect to get something back in hello.Photo = DisplayPhoto(hello.Photo);?
If you want to read something back from DisplayPhoto, probably you need to write something like this
public byte[] DisplayPhoto(byte[] photo)
{
if (!(photo == null))
{
MemoryStream stream = new MemoryStream();
// .......
return stream.ToArray();
}
else
{
// Convert your existing ResidentImage.Source to a byte array and return it
}
}
You are trying to set hello.Photo to the return value of DisplayPhoto yet it's return type is void, e.g. it returns nothing at all. Problematic line is here:
hello.Photo = DisplayPhoto(hello.Photo);
You need to make DisplayPhoto return a byte[]. Crude example: -
private byte[] DisplayPhoto(byte[] photo)
{
if (!(photo == null))
{
MemoryStream stream = new MemoryStream();
stream.Write(photo, 0, photo.Length);
stream.Position = 0;
System.Drawing.Image image = System.Drawing.Image.FromStream(stream);
BitmapImage bitmapImage = new BitmapImage();
bitmapImage.BeginInit();
MemoryStream memoryStream = new MemoryStream();
image.Save(memoryStream, System.Drawing.Imaging.ImageFormat.Bmp);
memoryStream.Seek(0, SeekOrigin.Begin);
bitmapImage.StreamSource = memoryStream;
bitmapImage.EndInit();
ResidentImage.Source = bitmapImage;
ResidentProfileImage.Source = bitmapImage;
return stream.ToArray();
}
else
{
ResidentImage.Source = new BitmapImage(new Uri("pack://application:,,,/Resources/ResidentImage.jpg"));
}
return new byte[0];
}