How to convert Image into byte[] in Android

泪湿孤枕 提交于 2021-01-22 12:18:28

问题


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();

回答1:


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);



回答2:


Like this:

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



回答3:


this function convert an image into array byte[]:

 public static byte[] getBitmapAsByteArray(Bitmap bitmap) {
    ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
    bitmap.compress(CompressFormat.PNG, 0, outputStream);       
    return outputStream.toByteArray();
}


来源:https://stackoverflow.com/questions/22116587/how-to-convert-image-into-byte-in-android

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!