在 Android 中将图像从可绘制对象转换为字节数组

Converting an image from drawable to byte array in Android

由于我要将图像发送到 Parse.com,因此我必须将其转换为字节数组。我的第一种方法是 select 来自图库的图像并将其转换为字节数组,如下所示:

 @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (requestCode == RESULT_LOAD_IMAGE && resultCode == RESULT_OK && null != data) {
             mMediaUri = data.getData();
            String[] filePathColumn = { MediaStore.Images.Media.DATA };

            Cursor cursor = getContentResolver().query(mMediaUri,
                    filePathColumn, null, null, null);
            cursor.moveToFirst();

            int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
            picturePath = cursor.getString(columnIndex);
            cursor.close();

           // ImageView imageView = (ImageView) findViewById(R.id.imgView);
            propertyImage.setImageBitmap(BitmapFactory.decodeFile(picturePath));

            Bitmap bmp = BitmapFactory.decodeFile(picturePath);
            ByteArrayOutputStream stream = new ByteArrayOutputStream();
            bmp.compress(Bitmap.CompressFormat.PNG, 100, stream);
            byteArray = stream.toByteArray();

        }

以上代码运行良好,图像已成功存储以进行解析。现在,当 select 没有图像时,我的应用程序崩溃了。显然 bcoz,没有发送数据并引发解析异常。

现在,我想设置一个默认图像,它位于我的可绘制文件夹中以进行解析,以防图库中没有图像 select,这样解析操作就不会受到干扰空数据。

我的方法是在开始时设置默认图像:

propertyImage=(ImageView)findViewById(R.id.imageViewOfImage);
        propertyImage.setImageResource(R.drawable.blank_image);

现在,如何将此默认图像转换为 ByteArray,以便将其发送进行解析?

感谢和问候

检查我的工作代码:

首先,您需要使用此方法将 drawable 图像转换为 Bitmap

 public static Bitmap drawableToBitmap(Drawable drawable) {
    if (drawable instanceof BitmapDrawable) {
        return ((BitmapDrawable) drawable).getBitmap();
    }

    final int width = !drawable.getBounds().isEmpty() ? drawable
            .getBounds().width() : drawable.getIntrinsicWidth();

    final int height = !drawable.getBounds().isEmpty() ? drawable
            .getBounds().height() : drawable.getIntrinsicHeight();

    final Bitmap bitmap = Bitmap.createBitmap(width <= 0 ? 1 : width,
            height <= 0 ? 1 : height, Bitmap.Config.ARGB_8888);

    Log.v("Bitmap width - Height :", width + " : " + height);
    Canvas canvas = new Canvas(bitmap);
    drawable.setBounds(0, 0, canvas.getWidth(), canvas.getHeight());
    drawable.draw(canvas);

    return bitmap;
}

获得位图对象后,您需要使用 byte 将其转换为数组。

ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 100, stream);
byte[] byteArray = stream.toByteArray();

它将帮助您转换 drawable --> ByteArray....

Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.image);
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 100, stream);
byte[] bitmapdata = stream.toByteArray();