转换ImageView以字节为单位android?

时间:2013-12-20 09:21:45

标签: android android-layout

我有一个ImageView,我正在为其分配一个使用zxing库生成的qr代码。

 <ImageView
        android:id="@+id/qrcode"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:layout_marginBottom="15dp"
        android:layout_marginTop="86dp" />

这是我的imageview,我想首先以字节为单位转换此ImageView,然后转换为bytearray。我可以实现吗?

3 个答案:

答案 0 :(得分:7)

如何将视图转换为位图

ImageView view = (ImageView)findViewById(R.id.qrcode);

view.setDrawingCacheEnabled(true);

view.buildDrawingCache();

Bitmap bm = view.getDrawingCache();

将位图转换为ByteArray

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

答案 1 :(得分:3)

image = (ImageView)findViewById(R.id.qrcode);
Bitmap bitmap = ((BitmapDrawable)image.getDrawable()).getBitmap();
ByteArrayOutputStream stream=new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 90, stream);
byte[] image=stream.toByteArray();
System.out.println("byte array:"+image);

String img_str = Base64.encodeToString(image, 0);
System.out.println("string:"+img_str);

答案 2 :(得分:0)

设置图片 - &gt; image=(Imageview)findViewById(R.id.imageview1);

转换为字节数组

Bitmap bitmap=BitmapFactory.decodeResource(getResources(), R.drawable.images);
        ByteArrayOutputStream stream=new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.PNG, 90, stream);
        byte[] image=stream.toByteArray();
        System.out.println("byte array:"+image);
        Log.d("array",image)
        String img_str = Base64.encodeToString(image, 0);
        Log.d("array_Str",image_str)
        System.out.println("string:"+img_str);