cant load the image from sqlite database in android - android

I tried to load an image from an database but the image is not loading,the logcat shows null
is it simethinf with the way i programmed..
imgdisplay = (ImageView) findViewById(R.id.imgIcon);
myDB = this.openOrCreateDatabase("hello", MODE_PRIVATE, null);
Cursor c = myDB.rawQuery(
"SELECT image FROM employee_details WHERE name= 'vv'", null);
if (c.getCount() > 0) {
c.moveToFirst();
do {
byte[] blob = c.getBlob(c.getColumnIndex("image"));
ImageView iv = (ImageView) findViewById(R.id.imgIcon);
iv.setImageBitmap(BitmapFactory.decodeByteArray(blob, 0,blob.length));
} while (c.moveToNext());
}
c.close();
myDB.close();
Logcat error is...
08-02 04:51:25.471: D/skia(8433): --- SkImageDecoder::Factory returned null

try below code..
byte[] Image_bytes = cursor.getBlob(cursor.getColumnIndex("image"));
ImageView iv = (ImageView) findViewById(R.id.imgIcon);
iv.setImageBitmap(new ImageConversation().convertArrayToBmp(Image_bytes));
...
public Bitmap convertArrayToBmp(byte[] array) {
Bitmap bitmap = BitmapFactory.decodeByteArray(array, 0, array.length);
return bitmap ;
}
use following loop
c.moveToFirst();
while(!c.isAfterLast()) {
byte[] blob = c.getBlob(c.getColumnIndex("image"));
ImageView iv = (ImageView) findViewById(R.id.imgIcon);
iv.setImageBitmap(BitmapFactory.decodeByteArray(blob, 0,blob.length));
c.moveToNext()
}

Try doing something like this -
If you are storing your image as String in database
if(image.isEmpty())
{
System.out.println("is empty image");
}
else
{
byte[] decodedByte = Base64.decode(image, 0);
Bitmap bm = BitmapFactory.decodeByteArray(decodedByte, 0,
decodedByte.length);
iv.setImageBitmap(bm);
}

I didn't find a method to save the image to the database so I started to save the image directly to the internal memory,this is not the answer for the question but may give some ideas to others who also don't have any idea to do...
To save into internal memory...
File fileWithinMyDir = getApplicationContext().getFilesDir();
try
{
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
.permitAll().build();
StrictMode.setThreadPolicy(policy);
URL url = new URL("http://t2.gstatic.com /images?q=tbn:ANd9GcQjZgUffqqe2mKKb5VOrDNd-ZxD7sJOU7WAHlFAy6PLbtXpyQZYdw");
File file = new File( fileWithinMyDir.getAbsolutePath() + "/" +"sun.jpg");
URLConnection ucon = url.openConnection();
InputStream is = ucon.getInputStream();
BufferedInputStream bis = new BufferedInputStream(is);
ByteArrayBuffer baf = new ByteArrayBuffer(50);
int current = 0;
while ((current = bis.read()) != -1)
{
baf.append((byte) current);
}
FileOutputStream fos = new FileOutputStream(file);
fos.write(baf.toByteArray());
fos.close();
}
catch (IOException e)
{
Log.e("download", e.getMessage());
}
To load image from internal memory..
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
.permitAll().build();
StrictMode.setThreadPolicy(policy);
mImgView1 = (ImageView) findViewById(R.id.mImgView1);
Bitmap bitmap = BitmapFactory.decodeFile(fileWithinMyDir.getAbsolutePath() + "/" +"sunn"+".file extension");
mImgView1.setImageBitmap(bitmap);
This is for newer android's that show error due to " android.os.networkonmainthreadexception"
u can also use AsyncTask if u want to solve the problem...

Related

Error in BitmapFactory.decodeByteArray

Hello
I have the following issue, i'm trying to retrieve the image from openweathermap.com, I have a service that access to the the page and retrieve the image as a byte array, I'm using the same service in an IOS app and work fine so I know that the service is working properly.
Service Code:
public byte[] GetWeatherIcon(string iconDesc)
{
byte[] result;
string url = "http://openweathermap.org/img/w/" + iconDesc + ".png";
Image image = RequestImage_Get(url, null, null, null);
System.Drawing.Imaging.ImageFormat format = System.Drawing.Imaging.ImageFormat.Png;
using (var ms = new MemoryStream())
{
image.Save(ms, format);
result = ms.ToArray();
}
return result;
}
In my Android application I'm executing the following code to access the service:
String urlIcon = SERVICEURL + "/GetWeatherIcon/" + weather.getWeather().get(0).getIcon();
InputStream iconStream = ExecuteRequestService(urlIcon);
BufferedReader rdIcon = new BufferedReader(new InputStreamReader(iconStream));
String jsonIcon = rdIcon.readLine();
JSONObject objIcon = new JSONObject(jsonIcon);
byte[] bytes = objIcon.getString("GetWeatherIconResult").getBytes("UTF-8");
final BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
Bitmap bmp = BitmapFactory.decodeByteArray(bytes, 0, bytes.length, options);
weather.setImage(bmp);
The method ExecuteRequestService code's is:
protected InputStream ExecuteRequestService(String url) throws Exception{
try{
URL urlObj = new URL(url);
HttpURLConnection conn = (HttpURLConnection) urlObj.openConnection();
conn.setRequestMethod("GET");
conn.setDoInput(true);
if(conn.getResponseCode() == 200) {
return conn.getInputStream();
}else {
return null;
}
}catch (Exception ex){
throw new Exception("An error occurred accessing MiOS server");
}
}
The error that i'm getting is: D/skia: --- SkImageDecoder::Factory returned null
I was reading a few post with the same exception but all of them are related with BitmapFactory.decodeStream but in my case is different as you can see but i can't find the problem, that's why i need your help
Here is an example of the url that I'm running so you can see the Json:Url running to get Json
Thanks in advanced
SkImageDecoder::Factory returned null ? You mean BitmapFactory.decodeByteArray() returns null ? Same cause as allways. Not enough memory. What's the size of the byte array? What's the size of the picture?
As private variable in your AsyncTask class:
Bitmap bmp = null;
In doinbackground:
JSONObject objIcon = new JSONObject(jsonIcon);
String thevalues = objIcon.get("GetWeatherIconResult").toString();
thevalues = thevalues.replace("[", "");
thevalues = thevalues.replace("]", "");
result = thevalues;
String values[] = thevalues.split(",");
byte bytes[] = new byte [values.length];
int nr = -1;
while (++nr < values.length)
{
int value = Integer.valueOf(values[nr]);
bytes[nr] = (byte)value;
}
bmp = BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
In onPostExecute:
if ( bmp != null )
{
ImageView imageView = (ImageView)MainActivity.this.findViewById ( R.id.imageView);
imageView.setImageBitmap(bmp);
}
Thank you so much for all your help, after break my neurons y found a good solution for this:
As you can see the structure of the json I was getting the byte array as String this is the code with the solution:
String urlIcon = SERVICEURL + "/GetWeatherIcon/" + weather.getWeather().get(0).getIcon();
InputStream iconStream = ExecuteRequestService(urlIcon);
BufferedReader rdIcon = new BufferedReader(new InputStreamReader(iconStream));
String jsonIcon = rdIcon.readLine();
JSONObject objIcon = new JSONObject(jsonIcon);
JSONArray jsonArray = objIcon.getJSONArray("GetWeatherIconResult");
byte[] bytes = new byte[jsonArray.length()];
for(int i=0; i<jsonArray.length(); i++){
bytes[i] = (byte) jsonArray.getLong(i);
}
Bitmap bmp = BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
weather.setImage(bmp);
I hope this help a few more like me.
simply use below code
byte[] img = Base64.decode(Service.GetImage(), Base64.DEFAULT);
Bitmap bitmap = BitmapFactory.decodeByteArray(img, 0, img.length);
imageid.setImageBitmap(getCircleBitmap(bitmap));

android get Image from URL and save in SQLite database and after setting it to Bitmap

I have the code for downloading image from URL to SDCard, but my device can set up the image ONLY from bitmap.
The question is how I can consume image from URL directly into SQLite Database and then retreive it as the bitmap?
Thanks for any help
public void getNewLogoFromURL(String logo) throws IOException {
new GetLogo().execute(logo);
}
class GetLogoForReceipt extends AsyncTask <String, Void, Void> {
#Override
protected Void doInBackground(String... params) {
try {
downloadFile(params[0]);
} catch ( IOException e ) {
}
return null;
}
}
public void downloadFile(String url) throws IOException {
DataOutputStream fos = null;
try {
File dest_file = new File("/sdcard/Pictures/applicationLogo.png");
URL u = new URL(url);
URLConnection conn = u.openConnection();
int contentLength = conn.getContentLength();
DataInputStream stream = new DataInputStream(u.openStream());
byte[] buffer = new byte[contentLength];
stream.readFully(buffer);
stream.close();
fos = new DataOutputStream(new FileOutputStream(dest_file));
fos.write(buffer);
fos.flush();
} finally {
fos.close();
}
}
//Device image settingUp code
String[] fileList = { "applicationLogo.png" };
Bitmap[] bitmap = new Bitmap[fileList.length];
BitmapFactory.Options options = new BitmapFactory.Options();
options.inPreferredConfig = Bitmap.Config.ARGB_8888;
Bitmap bitmap2 = BitmapFactory.decodeFile("/sdcard/Pictures/applicationLogo.png", options);
for ( int i = 0; i < fileList.length; i++ ) {
bitmap[i] = bitmap2;
}
int ret;
printer = new LinePrinter();
ret = printer.open(device);
ret = printer.setBitmap(bitmap);
Storing bitmaps/images in sqlite database is a bad idea. Download the image to the sd card and save the location in the data base and retrieve the image from sd card when you required.
The below code shows getting bitmap from sdcard.
public Bitmap createBitMap(String path){
File file = new File(path);
Bitmap bitmap = BitmapFactory.decodeFile(file.getAbsolutePath());
return bitmap;
}

Saving image from httpResponce

I have to download image from httpResponse and save it on internal storage on android device. I have this block of code trying to do that:
HttpResponse httpResponse = httpClient.execute(httpPost);
InputStream inputStream = httpResponse.getEntity().getContent();
Bitmap logo = BitmapFactory.decodeStream(inputStream);
FileOutputStream fos = null;
try {
fos = getApplicationContext().openFileOutput("logo.png",Context.MODE_PRIVATE);
logo.compress(Bitmap.CompressFormat.PNG, 90, fos);
} catch (FileNotFoundException e) {
e.printStackTrace();
} finally {
fos.close();
}
But I dont get the result I need. Saved image is does not open with image viewvers and its slighly bigger in size too. Image to download is 1.71 KB and the result is 2.01 KB. any ideas?
I don't know what's the real problem in your code but you can try this code if you want,this code ran without any problem for me
To save into internal memory...
File fileWithinMyDir = getApplicationContext().getFilesDir();
try
{
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
.permitAll().build();
StrictMode.setThreadPolicy(policy);
URL url = new URL("http://t2.gstatic.com /images?q=tbn:ANd9GcQjZgUffqqe2mKKb5VOrDNd-ZxD7sJOU7WAHlFAy6PLbtXpyQZYdw");
File file = new File( fileWithinMyDir.getAbsolutePath() + "/" +"sun.jpg");
URLConnection ucon = url.openConnection();
InputStream is = ucon.getInputStream();
BufferedInputStream bis = new BufferedInputStream(is);
ByteArrayBuffer baf = new ByteArrayBuffer(50);
int current = 0;
while ((current = bis.read()) != -1)
{
baf.append((byte) current);
}
FileOutputStream fos = new FileOutputStream(file);
fos.write(baf.toByteArray());
fos.close();
}
catch (IOException e)
{
Log.e("download", e.getMessage());
}
To load image from internal memory..
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
.permitAll().build();
StrictMode.setThreadPolicy(policy);
mImgView1 = (ImageView) findViewById(R.id.mImgView1);
Bitmap bitmap = BitmapFactory.decodeFile(fileWithinMyDir.getAbsolutePath() + "/" +"sunn"+".file extension");
mImgView1.setImageBitmap(bitmap);

android - storing image in internal storage

I an trying to store images downloaded from web to internal storage. I am refer following solution android - storing image cache in internal memory and reusing it
but still i am getting exception :
07-19 12:05:47.729: E/AndroidRuntime(341): java.lang.IllegalArgumentException: File /data/data/com.yellow.activity/files/-1717792749 contains a path separator
How to load image from filepath :
here is my code . image is an arraylist of URLs.
File fileWithinMyDir = getApplicationContext().getFilesDir();
for(int i=0; i<image.size();i++){
String filename = String.valueOf(image.get(i).hashCode());
String urlString = image.get(i);
String PATH = fileWithinMyDir.getAbsolutePath() + "/" +filename;
infoLog(PATH);
DownloadFromUrl(PATH, urlString);
img_path.add(PATH);
}
private void DownloadFromUrl(String fileName, String urlStr)
{
try
{
URL url = new URL(urlStr);
File file = new File(fileName);
URLConnection ucon = url.openConnection();
InputStream is = ucon.getInputStream();
BufferedInputStream bis = new BufferedInputStream(is);
ByteArrayBuffer baf = new ByteArrayBuffer(50);
int current = 0;
while ((current = bis.read()) != -1)
{
baf.append((byte) current);
}
FileOutputStream fos = new FileOutputStream(file,true);
fos.write(baf.toByteArray());
fos.close();
infoLog("going ryt....");
}
catch (IOException e)
{
infoLog("download "+ e.getMessage());
}
}
how to load image to imageView? I tried.
File filePath = getFileStreamPath(img_path.get(i));
imageView.setImageDrawable(Drawable.createFromPath(filePath.toString()));
but it didn't work.
To save into internal memory...
File fileWithinMyDir = getApplicationContext().getFilesDir();
try
{
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
.permitAll().build();
StrictMode.setThreadPolicy(policy);
URL url = new URL("http://t2.gstatic.com /images?q=tbn:ANd9GcQjZgUffqqe2mKKb5VOrDNd-ZxD7sJOU7WAHlFAy6PLbtXpyQZYdw");
File file = new File( fileWithinMyDir.getAbsolutePath() + "/" +"sun.jpg");
URLConnection ucon = url.openConnection();
InputStream is = ucon.getInputStream();
BufferedInputStream bis = new BufferedInputStream(is);
ByteArrayBuffer baf = new ByteArrayBuffer(50);
int current = 0;
while ((current = bis.read()) != -1)
{
baf.append((byte) current);
}
FileOutputStream fos = new FileOutputStream(file);
fos.write(baf.toByteArray());
fos.close();
}
catch (IOException e)
{
Log.e("download", e.getMessage());
}
To load image from internal memory..
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
.permitAll().build();
StrictMode.setThreadPolicy(policy);
mImgView1 = (ImageView) findViewById(R.id.mImgView1);
Bitmap bitmap = BitmapFactory.decodeFile(fileWithinMyDir.getAbsolutePath() + "/" +"sunn"+".file extension");
mImgView1.setImageBitmap(bitmap);
This is for newer android's that show error due to " android.os.networkonmainthreadexception"
u can also use AsyncTask if u want to solve the problem...
Try this way
String PATH = fileWithinMyDir.getAbsolutePath() + filename;
I solved it.
Replace following code
File filePath = getFileStreamPath(img_path.get(i));
imageView.setImageDrawable(Drawable.createFromPath(filePath.toString()));
with
imageView.setImageDrawable(Drawable.createFromPath(img_path.get(i)));

Storing images in SQLite android

I have an SQLite Database in which I am storing images as BLOB using this code
URL url = new URL("http://t0.gstatic.com/images?q=tbn:ANd9GcRsaLl3TGB4W2hJFN_Wh0DNVPQEYGtweNsqvTXVtwE8FXR300-Ut-npgS4");
//open the connection
URLConnection ucon = url.openConnection();
//buffer the download
InputStream is = ucon.getInputStream();
BufferedInputStream bis = new BufferedInputStream(is,128);
ByteArrayBuffer baf = new ByteArrayBuffer(128);
//get the bytes one by one
int current = 0;
while ((current = bis.read()) != -1) {
baf.append((byte) current);
}
mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE,null);
mydb.execSQL("INSERT INTO " + TABLE + "(IMAGE) VALUES('" + baf.toByteArray() + "')");
mydb.close();
When I try to retrive the image, I am getting the following error
Factory returned null
My Select Query is this
mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE,null);
Cursor allrows = mydb.rawQuery("SELECT * FROM "+ TABLE, null);
if(allrows.getCount() > 0){
allrows.moveToNext();
System.out.println("3333");
ImageView myImage = (ImageView) findViewById(R.id.ImageView01);
byte[] bb = allrows.getBlob(1);
System.out.println("VVV " + bb);
//convert it back to an image
ByteArrayInputStream imageStream = new ByteArrayInputStream(bb);
Bitmap theImage = BitmapFactory.decodeStream(imageStream);
myImage.setImageBitmap(theImage);
//myImage.setBackgroundResource(R.drawable.icon);
System.out.println("3333");
//myImage.setImageBitmap(BitmapFactory.decodeByteArray(bb, 0, bb.length));
}
Please anyone help.
I use decodeByteArray method
byte[] userPic1Blob = cursor.getBlob(cursor.getColumnIndex(SqlConstans.USER_PIC1_BLOB));
if(userPic1Blob != null && userPic1Blob.length > 0){
Bitmap bm = BitmapFactory.decodeByteArray(userPic1Blob, 0, userPic1Blob.length);
imageView.setImageBitmap(bm);
}

Categories

Resources