I've been searching for the past few days but did not manage to find a solution for my problem. I am currently working on a xamarin Android app. I want to display an image by using the byte array column from by database. I am using another program to find the byte array of a specific photo and after that I insert manually its value in the byte array column from my principal project.
This is my code where I am trying to reproduce the image:
Android.Graphics.Bitmap bitmap=BitmapFactory.DecodeByteArray(currentexercis.image, 0, currentexercis.image.Length);
viewHolder.exercis_photo.SetImageBitmap(bitmap);
Currentexercis.image represents the byte array from my database, and its value seems to be OK, however every time bitmap is null.
This is the code from my other program where I convert the image into bytearray:
Image img = Image.FromFile(opendlg.FileName);
MemoryStream ms = new MemoryStream();
img.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
dbpicEntities1 db = new dbpicEntities1();
db.MyPictures.Add(new MyPicture() { FileName=fileName, Data = ms.ToArray() });
db.SaveChanges();
MessageBox.Show("success");
I think you should use like this.
byte [] imageArray // is your data
MemoryStream mStream = new MemorySteram ();
mStream.write(imageArray,0,imageArray.Length);
Image img = Image.FromStream(mStream);
img.save(filelocation);
Bitmap bitmapimg = BitmapFactory.BitmapFactory.DecodeStream(mStream);
// if you want to use Bitmap
Byte Array to Image using C# in Xamarin
There are some third-party library which implements this feature quite well like Picasso or Glide.
For Glide, there is official document shows how to use it in Xamarin.Android project: Binding a .JAR.
Or you could directly use it from the nuget package:
Then you can code for example like this:
Glide.With(context)
.Load(imageBytes)
.Apply(RequestOptions.CircleCropTransform())
.Into(imageView);
convert to byteArray
byte[] imgdata = System.IO.File.ReadAllBytes(pathToImage);
convert byte array to bitmap
private void OnGetMemberAvatarCompleted(byte[] avatarBytes)
{
var avatarImageView = FindViewById<ImageView>(Resource.Id.memberProfile_avatar);
if (avatarImageView != null)
{
var imageBitmap = BitmapFactory.DecodeByteArray(avatarBytes, 0,avatarBytes.Length);
RunOnUiThread(() => avatarImageView.SetImageBitmap(imageBitmap));
}
}
Related
I need to convert a JBIG1 image to another image format, such as JPEG or PNG, but I can't seem to find anything related to this.
This JBIG1 image is received encoded in Base64.
I've tried using System.Drawing in .NET to accomplish this, but a "System.ArgumentException: Parameter is not valid" exception is thrown on calling Image.FromStream() using the JBIG1 byte array data.
See code below:
byte[] binData = ConvertFromBase64StringToArray("BASE64 ENCODED JBIG1 IMAGE GOES HERE");
Image img = binData.ConvertToImage();
img.Save("C:/Images/converted-from-jbig.jpeg", System.Drawing.Imaging.ImageFormat.Jpeg);
Functions used:
public static byte[] ConvertFromBase64StringToArray(string base64String)
{
byte[] data = Convert.FromBase64String(base64String);
using (var stream = new MemoryStream(data, 0, data.Length))
{
data = stream.ToArray();
}
return data;
}
public static Image ConvertToImage(this byte[] byteArrayIn)
{
var ms = new MemoryStream(byteArrayIn);
Image returnImage = Image.FromStream(ms); //exception thrown in this line
return returnImage;
}
Does anyone have any knowledge to share about this topic?
You'll probably need a third party library to work with JBig files. It looks like https://github.com/dlemstra/Magick.NET has support for that.
I have 2 solutions in this project. A windows forms solution and a Windows 8.1 Tablet project.
This is what's supposed to happen:
User takes a picture using the tablet and uploads it to a MySQL database in the form of a byte array.
User starts up the windows forms application and loads the byte array from the MySQL database.
It then converts the byte array to an image which is placed in a picturebox.
I'm storing the byte array like this:
CameraCaptureUI dialog = new CameraCaptureUI();
dialog.PhotoSettings.Format = CameraCaptureUIPhotoFormat.Jpeg;
Size aspectRatio = new Size(16, 9);
dialog.PhotoSettings.CroppedAspectRatio = aspectRatio;
StorageFile file = await dialog.CaptureFileAsync(CameraCaptureUIMode.Photo);
if (file != null)
{
BitmapImage bitmapImage = new BitmapImage();
using (IRandomAccessStream fileStream = await file.OpenAsync(FileAccessMode.Read))
{
var readStream = fileStream.AsStreamForRead();
byte[] pixeBuffer = new byte[readStream.Length];
await readStream.ReadAsync(pixeBuffer, 0, pixeBuffer.Length);
}
The byte array is successfully stored in my database.
I'm running into a problem when converting the byte array into a WinForms Image.
This is my code:
using (var ms = new MemoryStream(bytes))
{
Image i = Image.FromStream(ms);
return i;
}
This gives me an invalid parameter exception.
I'm guessing it's something with the image format? I'm really new to streams though so I have no idea.
Any help is welcome!
PS: I know storing in the SQL database runs perfectly since I can store and load images perfectly using the WinForms application only.
Have you tried setting the position of the MemoryStream back to the beginning before trying to create the Image...
ms.Seek(0, SeekOrigin.Begin);
using (MemoryStream ms = new MemoryStream())
{
WriteableBitmap btmMap = new WriteableBitmap
(bitmapImage.PixelWidth, bitmapImage.PixelHeight);
return ms.ToArray();
}
Try it ,
it's working with me
I'm working with Microsoft's OCR library and am having problems converting the BitmapImage to a pixel array.
I'm making this application for Windows Phone 8, and WriteableBitmap.PixelBuffer.ToArray() isn't an option so I have a static function that'll change a normal BitmapImage into a byte array to feed into the OCR engine.
Well, every time I feed it in the application crashes. What's wrong here?
Here is my static class with the bitmap converter
public static class ByteArrayChange
{
public static byte[] ConvertToBytes(this BitmapImage bitmapImage)
{
byte[] data = null;
using (MemoryStream stream = new MemoryStream())
{
WriteableBitmap wBitmap = new WriteableBitmap(bitmapImage);
wBitmap.SaveJpeg(stream, wBitmap.PixelWidth, wBitmap.PixelHeight, 0, 100);
stream.Seek(0, SeekOrigin.Begin);
data = stream.GetBuffer();
}
return data;
}
}
Here is the piece of code in the OCR method that's causing the application to crash.
byte[] pa = ByteArrayChange.ConvertToBytes(bitmap);
//Here Is he problem
var ocrResult = await ocrEngine.RecognizeAsync((uint)bitmap.PixelHeight, (uint)bitmap.PixelWidth, pa);
What am I doing wrong here?
Thanks!
You're saving your image as JPEG, but I'm fairly certain that OCR library accept RGB/BGRA as an input.
So why don't you use Pixels property? It represents image as BGRA array, so the only thing you need is to convert it to byte[] array.
I'm developing a control where user can set an image and i want this this to be as user friendly as possible - so support for copy & paste, drag & drop.
I've got this part working using IDataObjects, testing for fileformats of FileDrop, FileContents (eg from outlook), and bitmap eg:
private void GetImageFromIDataObject(IDataObject myIDO)
{
string[] dataformats = myIDO.GetFormats();
Boolean GotImage = false;
foreach (string df in dataformats)
{
if (df == DataFormats.FileDrop)
{
// code here
}
if (df == DataFormats.Bitmap)
{
// Source of my problem here... this gets & displays image but
// how do I then convert from here ?
ImageSource myIS = Utilities.MyImaging.ImageFromClipboardDib();
ImgPerson.Source = myIS;
}
}
}
The ImageFromClipboard code is Thomas Levesque's as referenced in the answer to this SO question wpf InteropBitmap to bitmap
http://www.thomaslevesque.com/2009/02/05/wpf-paste-an-image-from-the-clipboard/
No matter how I get the image onto ImgPerson, this part is working fine; image displays nicely.
When user presses save I need to convert the image to a bytearray and send to a WCF server which will save to server - as in, reconstruct the bytearray into an image and save it in a folder.
For all formats of drag & drop, copy & paste the image is some form of System.Windows.Media.Imaging.BitmapImage.
Except for those involving the clipboard which using Thomas's code becomes System.Windows.Media.Imaging.BitmapFrameDecode.
If I avoid Thomas's code and use:
BitmapSource myBS = Clipboard.GetImage();
ImgPerson.Source = myBS;
I get a System.Windows.Interop.InteropBitmap.
I can't figure out how to work with these; to get them into a bytearray so I can pass to WCF for reconstruction and saving to folder.
Try this piece of code
public byte[] ImageToBytes(BitmapImage imgSource)
{
MemoryStream objMS = new MemoryStream();
PngBitmapEncoder encoder = new PngBitmapEncoder();
encoder.Frames.Add(BitmapFrame.Create(imgSource));
encoder.Save(objMS);
return objMS.GetBuffer();
}
You can also use JpegBitmapEncoder, BmpBitmapEncoder based on your requirements.
byte[] arr = ImageToBytes(ImgPerson.Source as BitmapImage);
I can't believe I didn't see this SO question but the this is essentially the same as my question:
WPF: System.Windows.Interop.InteropBitmap to System.Drawing.Bitmap
The answer being:
BitmapSource bmpSource = msg.ThumbnailSource as BitmapSource;
MemoryStream ms = new MemoryStream();
BitmapEncoder encoder = new PngBitmapEncoder();
encoder.Frames.Add(BitmapFrame.Create(bmpSource));
encoder.Save(ms);
ms.Seek(0, SeekOrigin.Begin);
System.Drawing.Bitmap bitmap = new System.Drawing.Bitmap(ms);
So similar in execution to Nitesh's answer but crucially, works with an inter-op bitmap.
I have the following code in c# which convert image to the byte[]
MemoryStream memory = new MemoryStream();
bitmap.Save(memory, System.Drawing.Imaging.ImageFormat.Jpeg);
now i want to get the image back in the android, what should i do ?
Im not really sure what your problem is as you haven't answered anyones question but if you just want to make a bitmap out of a byte array this how to do it
BitmapFactory.Options opt = new BitmapFactory.Options();
opt.inPreferredConfig = Bitmap.Config.ARGB_8888;
Bitmap bitmap = BitmapFactory.decodeByteArray(data, 0, data.length, opt);
Convert ByteArray to Base64 string in C#. Then Convert Base64 string to ByteArray in android an do everything you want. In this method you can work with any object type in addition to bitmap.