I am going to create an activity feed like this:
and I wonder, how will I retrieve the image and how to store it in my MySQL database. Help me out!
I am going to create an activity feed like this:
and I wonder, how will I retrieve the image and how to store it in my MySQL database. Help me out!
Here is how to do it
To download the image use the Universal Image Loader
ImageLoader imageLoader = ImageLoader.getInstance();
imageLoader.init(ImageLoaderConfiguration.createDefault(context));
OR
ImageLoaderConfiguration config = new
ImageLoaderConfiguration.Builder(context)
.maxImageWidthForMemoryCache(800)
.maxImageHeightForMemoryCache(480)
.httpConnectTimeout(5000)
.httpReadTimeout(20000)
.threadPoolSize(5)
.threadPriority(Thread.MIN_PRIORITY + 3)
.denyCacheImageMultipleSizesInMemory()
.build();
imageLoader.init(config);
options = new DisplayImageOptions.Builder()
.showStubImage(R.drawable.loading)
.cacheInMemory()
.cacheOnDisc()
.build();
imageLoader.displayImage(ProductsImageURL,imagView,options, new ImageLoadingListener(){});
In this ImageLoadingListener you get a method that is called when loading is done and save the image as string
or make any http connection to download the image as here How to download and save an image in Android
Once the image is downloaded convert it into string and store it in database
public Bitmap StringToBitMap(String encodedString) {
try {
byte[] encodeByte = Base64.decode(encodedString, Base64.DEFAULT);
Bitmap bitmap = BitmapFactory.decodeByteArray(encodeByte, 0,
encodeByte.length);
return bitmap;
} catch (Exception e) {
e.getMessage();
return null;
}
}
public String BitMapToString(Bitmap bitmap) {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 100, baos);
byte[] b = baos.toByteArray();
String temp = Base64.encodeToString(b, Base64.DEFAULT);
return temp;
}
Here are the general steps if you want to store the image itself into your database.
i. Retrieve the image using its URL and keep it in memory as a byte[]. There are several ways to do this, including creating a ByteArrayBuffer and appending bytes to its end. You can then retrieve the final byte[] with ByteArrayBuffer.toByteArray().
ii. You need to create a table with a column of type BLOB, e.g.
CREATE TABLE image (id INTEGER PRIMARY KEY AUTOINCREMENT, url TEXT, data BLOB)
iii. You would then insert the image byte[] as you would any other data type, for example by create a ContentValues and then passing it to SQLiteDatabase.insert().
iv. Retrieve the byte[] from SQLite and build an image. Use Cursor.getBlob() to grab the byte[] and then do:
ByteArrayInputStream byteArrayImageStream = new ByteArrayImageStream(yourByteArray);
Bitmap yourImage = BitmapFactory.decodeStream(byteArrayImageStream);