Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert Image into byte[] in Android

I want to save image in sqlite. In this method I have got image path into string. My Question is How to convert it into byte[] format.

if (resultCode == RESULT_OK) {
// we need to update the gallery by starting MediaSanner service.
mScanner = new MediaScannerConnection(ImagePreviewActivity.this,new MediaScannerConnection.MediaScannerConnectionClient() {

                        public void onMediaScannerConnected() {
                                mScanner.scanFile(imageUri.getPath(), null );
                        }           

                        public void onScanCompleted(String path, Uri uri) {
                            mScanner.disconnect();
                            if (path.equals(imageUri.getPath())) {
                                 photoPath=imageUri.getPath();
                                        ImagePreviewActivity.this.runOnUiThread(new Runnable() {
                                        public void run() {
                                            capture_photo = (ImageView) findViewById(R.id.caturePhoto);
                                            Bitmap myBitmap = BitmapFactory.decodeFile(photoPath);
                                            capture_photo.setImageBitmap(myBitmap);

                                    }
                                });
                                mScanner.disconnect();
                            }
                        }
                    });
                    mScanner.connect();
like image 296
Ash Avatar asked Mar 01 '14 15:03

Ash


2 Answers

First convert ImagePath to Bitmap

       Bitmap src=BitmapFactory.decodeFile(imagePath);

Convert bitmap into byte array using this code:

        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        src.compress(Bitmap.CompressFormat.PNG, 100, baos);
        data = baos.toByteArray();

After your question in comment

To show byte array into imageview use these lines of code:

   Bitmap bitmap = BitmapFactory.decodeByteArray(bitmapdata , 0, bitmapdata .length);

    imageView.setImageBitmap(bitmap);

To show imagePath into imageView you can use

                 Bitmap src=BitmapFactory.decodeFile(imagePath);
                 imageView.setImageBitmap(bitmap);
like image 157
Abhishek Agarwal Avatar answered Oct 02 '22 17:10

Abhishek Agarwal


Like this:

ByteArrayOutputStream stream = new ByteArrayOutputStream();
myBitmap.compress(Bitmap.CompressFormat.PNG, 100, stream);
byte[] byteArray = stream.toByteArray();
like image 36
Rolf ツ Avatar answered Oct 02 '22 19:10

Rolf ツ