I am getting an error while instantiating ExifReader in Windows Phone 8 C#. Please find the code snippet below. Kindly do the needful
Error : "ExifLib requires a seekable stream"
byte[] imageBytes = (byte[])PhoneApplicationService.Current.State["ViewImage"];
MemoryStream ms = new MemoryStream(imageBytes,0,imageBytes.Length);
BitmapImage bitmapImage = new BitmapImage();
bitmapImage.SetSource(ms);
try
{
ExifReader xif = new ExifReader(toStream(bitmapImage)); // Getting Error here
double gpsLat, gpsLng;
xif.GetTagValue<double>(ExifTags.GPSLatitude, out gpsLat);
xif.GetTagValue<double>(ExifTags.GPSLongitude, out gpsLng);
map.Center = new System.Device.Location.GeoCoordinate(gpsLat, gpsLng);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message.ToString());
}
Stream toStream(BitmapImage img)
{
WriteableBitmap bmp = new WriteableBitmap((BitmapSource)img);
using (MemoryStream stream = new MemoryStream())
{
bmp.SaveJpeg(stream, bmp.PixelWidth, bmp.PixelHeight, 0, 100);
stream.Position = 0;
return stream;
}
}
Your MemoryStream is returning false when CanSeek is called. This is because you've wrapped your MemoryStream in a using statement, which means that you're returning a disposed object.
Your toStream method should actually look like this:
Stream ToStream(BitmapImage img)
{
MemoryStream stream = new MemoryStream();
using (WriteableBitmap bmp = new WriteableBitmap((BitmapSource)img))
{
bmp.SaveJpeg(stream, bmp.PixelWidth, bmp.PixelHeight, 0, 100);
}
stream.Position = 0;
return stream;
}
Related
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;
}
}
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 wanna save a picture that loaded in a picturebox to stream .when i save in png format it work properly but when i want save it in other formats i get
A Generic error occured in GDI + exception
its my code:
Image Img = pictureBox1.Image;
byte[] inputImage = new byte[Img.Width * Img.Height];
System.IO.MemoryStream ms = new System.IO.MemoryStream();
ms.Read(inputImage, 0, Img.Width * Img.Height);
if (System.Drawing.Imaging.ImageFormat.Jpeg.Equals(Img.RawFormat))
{
pictureBox1.Image.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
}
else if (System.Drawing.Imaging.ImageFormat.Gif.Equals(Img.RawFormat))
{
ms.Seek(0, SeekOrigin.Begin);
pictureBox1.Image.Save(ms, System.Drawing.Imaging.ImageFormat.Gif);
}
else if (System.Drawing.Imaging.ImageFormat.Png.Equals(Img.RawFormat))
{
pictureBox1.Image.Save(ms, System.Drawing.Imaging.ImageFormat.Png);
}
else if (System.Drawing.Imaging.ImageFormat.Bmp.Equals(Img.RawFormat))
{
pictureBox1.Image.Save(ms, System.Drawing.Imaging.ImageFormat.Bmp);
}
Try this method:
public Stream ImageToStream(Image image, System.Drawing.Imaging.ImageFormat format)
{
MemoryStream ms = new MemoryStream();
image.Save(ms, format);
return ms;
}
and use it:
using(Stream stream = ImageToStream(pictureBox1.Image,
System.Drawing.Imaging.ImageFormat.Gif))
{
...
}
I've got WCF service to send image as a stream to client app.
My client app gets the stream :
Stream imageStream = client.GetImage();
When I use this code:
imageStream.CopyTo(stream);
int size = (int)stream.Length;
stream.Seek(0, SeekOrigin.Begin);
BitmapFrame bf = BitmapFrame.Create(stream,
BitmapCreateOptions.None,
BitmapCacheOption.OnLoad);
cam_img.Source = bf;
It work's fine but I need apply some filters to image before assign to source.
So I need bitmap. First, I convert Stream imageStream to byte array and then I use some code I find on forums:
byte[] tab_img;
using (var memoryStream = new MemoryStream())
{
imageStream.CopyTo(memoryStream);
tab_img= memoryStream.ToArray();
}
Bitmap bm;
using (MemoryStream mStream = new MemoryStream())
{
mStream.Write (tab_img, 0, tab_img.Length);
mStream.Seek(0, SeekOrigin.Begin);
bm = new Bitmap(mStream);
Grayscale filter = new Grayscale(0.2125, 0.7154, 0.0721);
Bitmap bm_post = filter.Apply(bm);
ImageSourceConverter c = new ImageSourceConverter();
object source = new ImageSourceConverter().ConvertFrom(bm_post);
ImageSource is1 = (ImageSource)source;
cam_img.Source = is1;
}
but I still get NullReferenceException in line
object source = new ImageSourceConverter().ConvertFrom(bm_post);
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];
}