简体   繁体   中英

How to Insert Image in Sqlite Database?

here I want to send my image in database.. but i Can't assign imgPro to values.put.. Please help me..

else if (requestCode == 2) {

            Uri selectedImage = data.getData();
            String[] filePath = { MediaStore.Images.Media.DATA };
            Cursor c = getContentResolver().query(selectedImage, filePath, null, null, null);
            c.moveToFirst();
            int columnIndex = c.getColumnIndex(filePath[0]);
            String picturePath = c.getString(columnIndex);
            c.close();
            Bitmap thumbnail = (BitmapFactory.decodeFile(picturePath));
            imgPro.setImageBitmap(thumbnail);


        }

You can do like below.

   public class ImageConverter {

    public static String imageToStringConverter(Bitmap image){
        ByteArrayOutputStream stream = new ByteArrayOutputStream();
        image.compress(Bitmap.CompressFormat.PNG, 100, stream);
        byte[] byteArray = stream.toByteArray();
        String imageToString = Base64.encodeToString(byteArray, Base64.NO_WRAP);
        return imageToString;
    }

    public static Bitmap stringToimageConverter(String imageString){
        byte[] stringTobyte = Base64.decode(imageString, Base64.NO_WRAP);
        Bitmap bmp = BitmapFactory.decodeByteArray(stringTobyte, 0, stringTobyte.length);
        return bmp;
    }

}

You will call this two function to convert the image into string and then save in the database.Like below

String statusImage = ImageConverter.imageToStringConverter(selectedImage);

selectedImage is the bitmap you have selected from file. and if u want show the image then just again convert the string back to image.
Now why Base64??

When you have some binary data that you want to ship across a network, you generally don't do it by just streaming the bits and bytes over the wire in a raw format. Why? because some media are made for streaming text. You never know -- some protocols may interpret your binary data as control characters (like a modem), or your binary data could be screwed up because the underlying protocol might think that you've entered a special character combination (like how FTP translates line endings).

So to get around this, people encode the binary data into characters. Base64 is one of these types of encodings. Why 64? Because you can generally rely on the same 64 characters being present in many character sets, and you can be reasonably confident that your data's going to end up on the other side of the wire uncorrupted.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM