user6760779
user6760779

Reputation:

How to save Drawable after setColorFilter on Android

To apply color-filter to byte array that comes from takePicure() method, I converted it to Drawable. And after calling Drawable.setColorFilter(), I saved it as a image file. But, color-filter doesn't apply to image file. In this case, how to save the drawable applied color-filter. Here is my code.

Camera.PictureCallback mPicture = new Camera.PictureCallback() {
        @Override
        public void onPictureTaken(byte[] bytes, Camera camera) {
            mView.mRenderer.restartPreview();
            String storageDir = Environment.getExternalStorageDirectory().getAbsolutePath()
                    + "/" + Environment.DIRECTORY_DCIM + "/Camera";
            File dir = new File(storageDir);

            if (!dir.exists()) dir.mkdir();

            String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
            String path = storageDir + "/IMG_" + timeStamp + ".jpg";

            File file = new File(path);
            try {
                ColorMatrix matrix = new ColorMatrix(new float[] {
                        1, 0, 0, 0, mView.mRenderer.mTest,
                        0, 1, 0, 0, mView.mRenderer.mTest,
                        0, 0, 1, 0, mView.mRenderer.mTest,
                        0, 0, 0, 1, 0
                });

                Drawable image = new BitmapDrawable(BitmapFactory.decodeByteArray(bytes, 0, bytes.length));
                image.setColorFilter(new ColorMatrixColorFilter(matrix));
                Bitmap bitmap = ((BitmapDrawable)image).getBitmap();
                ByteArrayOutputStream stream = new ByteArrayOutputStream();
                bitmap.compress(Bitmap.CompressFormat.JPEG, 100, stream);
                byte[] bytedata = stream.toByteArray();

                FileOutputStream fos = new FileOutputStream(file);
                fos.write(bytedata);
                fos.flush();
                fos.close();

                Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
                Uri uri = Uri.parse("file://" + path);
                intent.setData(uri);
                sendBroadcast(intent);
            }
            catch (Exception e) {
                Log.e("CheckLog", e.getMessage());
                return;
            }
        }
};

mView.mRenderer.mTest is a variable controlled by SeekBar. Thanks in advance.

Upvotes: 1

Views: 1579

Answers (1)

Dhara Chandarana
Dhara Chandarana

Reputation: 166

Use canvas for applying matrix.

Bitmap bitmap = Bitmap.createBitmap(original.getWidth(), 
original.getHeight(), Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(bitmap);

Paint paint = new Paint();
paint.setColorFilter(new ColorMatrixColorFilter(
matrix));
canvas.drawBitmap(original, 0, 0, paint);

return bitmap;

Upvotes: 7

Related Questions