代码之家  ›  专栏  ›  技术社区  ›  Prescott Chartier

Android Xamarin-检索存储在imageview中的图像

  •  0
  • Prescott Chartier  · 技术社区  · 6 年前

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

    在某个时候,图像被更改了,我需要将其存储回数据库中。如何从imageview中获取图像?到目前为止,我所看到的一切都是关于一个附加的可提取的,在这种情况下没有可提取的。

    Bitmap photo = imageview.GetCurrentImage();
    

    ****更新****

    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'”

    1 回复  |  直到 6 年前
        1
  •  0
  •   FreakyAli    6 年前

    你需要做的事情如下:

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

    更新:

       byte[] bitmapData;
       using (var stream = new MemoryStream())
       { 
      bitmap.Compress(Bitmap.CompressFormat.Png, 0, stream);
        bitmapData = stream.ToArray();
       }