Thursday, February 21, 2019

Passing image to another activity

We want to pass a picture to another activity. For example, a screenshot of running app.
Use this code.
layout.setDrawingCacheEnabled(true);              layout.setDrawingCacheQuality(LinearLayout.DRAWING_CACHE_QUALITY_HIGH);
layout.buildDrawingCache();
Bitmap b = layout.getDrawingCache();
ByteArrayOutputStream stream = new ByteArrayOutputStream();
b.compress(Bitmap.CompressFormat.PNG, 100, stream);
byte[] byteArray = stream.toByteArray();
Intent in = new Intent(MainActivity.this, newclass.class);
in.putExtra("image",byteArray);                 
startActivity(in);
layout is the LinearLayout you set for screen that take picture.
In new class, we receive bitmap image and set it to imageView.
byte[] byteArray = getIntent().getByteArrayExtra("image");
Bitmap bmp = BitmapFactory.decodeByteArray(byteArray, 0, byteArray.length);
image.setImageBitmap(bmp);

If picture too large, we want to resize it to smaller, about 60% of original size.
int srcWidth = bmp.getWidth();
int srcHeight = bmp.getHeight();
int dstWidth = (int)(srcWidth*0.6f);
int dstHeight = (int)(srcHeight*0.6f);
image.setImageBitmap(Bitmap.createScaledBitmap(bmp, dstWidth, dstHeight, true));

No comments:

Post a Comment