Android Xamarin - 检索存储在图像视图中的图像 [英] Android Xamarin - retrieve the image stored in an imageview

查看:28
本文介绍了Android Xamarin - 检索存储在图像视图中的图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我检索图像作为存储在数据库中的字节数组,将其转换为位图并在 Imageview 中显示.我希望能够从 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.

似乎没有这样的方法:

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;
    }
}

这会生成一个异常无法从 'java/nio/HeapByteBuffer' 转换为 '[B'"

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

推荐答案

你需要做的事情如下:

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

其中 imageView 是您希望从中获取位图的 imageView 控件

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

更新:

像这样从位图转换为 byteArray:

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();
   }

这篇关于Android Xamarin - 检索存储在图像视图中的图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆