How to save images into Database

前端 未结 3 1812
迷失自我
迷失自我 2020-11-27 17:27

I\'d like to know if there\'s a way to save Images (of the type .gif) to the sqllite-database. If yes how should my DatabaseAdapter look like.

Also is t

相关标签:
3条回答
  • 2020-11-27 18:15

    There's nothing special in storing image to SQLite. Just create table with BLOB record type and do smth like:

    protected long saveBitmap(SQLiteDatabase database, Bitmap bmp)
    {
        int size = bmp.getRowBytes() * bmp.getHeight(); 
        ByteBuffer b = ByteBuffer.allocate(size); bmp.copyPixelsToBuffer(b); 
        byte[] bytes = new byte[size];
        b.get(bytes, 0, bytes.length);
        ContentValues cv=new ContentValues();
        cv.put(CHUNK, bytes);
        this.id= database.insert(TABLE, null, cv);
    }
    

    Probably you migth want to save image chunk by chunk, since there's limits/recommended BLOB size (don't really recall how much)

    0 讨论(0)
  • 2020-11-27 18:16

    Check this tutorial, it should show you what you need.
    Another useful link.

    0 讨论(0)
  • 2020-11-27 18:20

    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.

    0 讨论(0)
提交回复
热议问题