How to save images into Database

You should use BLOB in your database:

Check this tutorial

But I think you should download and store image in HashMap, which will make it simpler.

Code:

Stroring

var imageMap = new HashMap<String, byte[]>();

var imageUrl = "http://i.stack.imgur.com/TLjuP.jpg";

var imagedata = GetImage(imageUrl);      

imageMap.put("img",imagedata);

Retrieving

var imageData = imageMap.get("img");

var imageStream = new ByteArrayInputStream(imageData);

var image = BitmapFactory.decodeStream(imageStream);

GetImage

private byte[] GetImage(String url)
{
    try
    {
        var imageUrl = new URL(url);
        var urlConnection = imageUrl.openConnection();

        var inputStream = urlConnection.getInputStream();
        var bufferedInputStream = new BufferedInputStream(inputStream);

        var byteArrayBuffer = new ByteArrayBuffer(500);

        int current = 0;
        while ((current = bis.read()) != -1)
        {
            byteArrayBuffer.append((byte)current);
        }

        return byteArrayBuffer.toByteArray();
    }
    catch (Exception e)
    {
        Log.d("ImageManager", "Error: " + e.toString());
        return null;
    }       
}

Hope it helps you.

Leave a Comment