Android Xamarin - retrieve the image stored in an imageview

问题: I retrieve an image as a byte arrary stored in a database convert it to a bitmap and display it in an Imageview. I want to be able to retrieve that image from the Imageview...

问题:

I retrieve an image as a byte arrary stored in a database convert it to a bitmap and display it in an Imageview. I want to be able to retrieve that image from the Imageview and store it back to the database. My database retrieval code is:

TheService myService = new TheService.DataInterface();
DataSet MyPhoto = myService.GetPhoto(id);
byte[] imageBytes = (byte[])MyPhoto.Tables[0].Rows[0][0];
Bitmap bitmap = BitmapFactory.DecodeByteArray(imageBytes, 0, imageBytes.Length);
imageview.SetImageBitmap(bitmap);

At some point the image is changed and I need to store it back in the database. How would I get the image out of the imageview? Everything I've seen thus far deals with an attached drawable, there is no drawable in this case.

There doesn't seem to be a method like:

Bitmap photo = imageview.GetCurrentImage();

Any assistance would be appreciated.

**** UPDATED ****

Once I get the image I need to convert it into a byte array to save it into the database. I've tried several different methods with no success, the latest is:

using Java.Nio;
public static byte[] ImageToByte(Bitmap bitmap)
{
    var bytes = new Byte[30000];
    try
    {
        var byteBuffer = ByteBuffer.Allocate(bitmap.ByteCount);
        bitmap.CopyPixelsToBuffer(byteBuffer);
        bytes = byteBuffer.ToArray<byte>();
        return bytes;
    }
    catch (Exception ex)
    {
        var message = ex.Message;
        return bytes;
    }
}

This generates an exception "Unable to cast from 'java/nio/HeapByteBuffer' to '[B'"


回答1:

What you need to do is something like below:

   BitmapDrawable bitmapDrawable = ((BitmapDrawable) imageView.Drawable);
    Bitmap bitmap;
    if(bitmapDrawable==null){
        imageView.BuildDrawingCache();
        bitmap = imageView.GetDrawingCache();
        imageView.BuildDrawingCache(false);
    }else
    {
        bitmap = bitmapDrawable .Bitmap;
    }

Where imageView is the imageView control from which you want your bitmap

Update:

Convert from bitmap to byteArray something like this:

   byte[] bitmapData;
   using (var stream = new MemoryStream())
   { 
  bitmap.Compress(Bitmap.CompressFormat.Png, 0, stream);
    bitmapData = stream.ToArray();
   }
  • 发表于 2019-03-12 06:53
  • 阅读 ( 412 )
  • 分类:sof

条评论

请先 登录 后评论
不写代码的码农
小编

篇文章

作家榜 »

  1. 小编 文章
返回顶部
部分文章转自于网络,若有侵权请联系我们删除