BitmapFactory returns null - android

I am working on an application where I am getting an image from the web server.
I need to save that image in a sqlite database. Maybe it will be saved in a byte[]; I have done this way, taking the datatype as blob, and then retrieving the image from db and showing at imageview.
I am stuck somewhere, however: I am getting null when I decodefrom bytearray
The code I have used is:
InputStream is = null;
try {
URL url = null;
url = new URL(http://....);
URLConnection ucon = null;
ucon = url.openConnection();
is = ucon.getInputStream();
} catch (MalformedURLException e1) {
e1.printStackTrace();
} catch (IOException e1) {
e1.printStackTrace();
}
BufferedInputStream bis = new BufferedInputStream(is);
ByteArrayBuffer barb = new ByteArrayBuffer(128);
int current = 0;
try {
while ((current = bis.read()) != -1) {
barb.append((byte) current);
} catch (IOException e) {
e.printStackTrace();
}
byte[] imageData = barb.toByteArray();
Then I have inserted imageData in to the db..
To retrieve the image:
byte[] logo = c.getBlob(c.getColumnIndex("Logo_Image"));
Bitmap bitmap = BitmapFactory.decodeByteArray(logo, 0, logo.length);
img.setImageBitmap(bitmap);
But I am getting the error:
Bitmap bitmap is getting null.

Sometimes, It happens, when your byte[] not decode properly after retrieving from database as blob type.
So, You can do like this way, Encode - Decode,
Encode the image before writing to the database:
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
mBitmap.compress(Bitmap.CompressFormat.JPEG, THUMB_QUALITY, outputStream);
mByteArray = outputStream.toByteArray(); // write this to database as blob
And then decode it like the from Cursor:
ByteArrayInputStream inputStream = new ByteArrayInputStream(cursor.getBlob(columnIndex));
Bitmap mBitmap = BitmapFactory.decodeStream(inputStream);
Also, If this not work in your case, then I suggest you to go on feasible way..
Make a directory on external / internal storage for your application
images.
Now store images on that directory.
And store the path of those image files in your database. So you
don't have a problem on encoding-decoding of images.

Related

bitmap.compress from Uri resulting in OutOfMemoryError

I am trying to save a bitmap which user selects into my own App path.
Unfortunately, with very big images I get OutOfMemoryError error.
I am using the following code:
private String loadImage (Uri filePath) {
File fOut = new File(getFilesDir(),"own.jpg");
inStream = getContentResolver().openInputStream(filePath);
selectedImage = BitmapFactory.decodeStream(inStream);
selectedImage.compress(CompressFormat.JPEG, 100, new FileOutputStream(fOut));
}
Is there any way for me to save any image file of any size for an Uri to a file?
*I am not in a position to resize the image e.g. by using calculateInSampleSize method.
Is there any way for me to save any image file of any size for an Uri to a file?
Since it already is an image, just copy the bytes from the InputStream to the OutputStream:
private void copyInputStreamToFile( InputStream in, File file ) {
try {
FileOutputStream out = new FileOutputStream(file);
byte[] buf = new byte[8192];
int len;
while((len=in.read(buf))>0){
out.write(buf,0,len);
}
out.flush();
out.getFD().sync();
out.close();
in.close();
} catch (Exception e) {
e.printStackTrace();
}
}
(adapted from this SO answer)

Save & retrieve images from SQLite database

I'm trying to save the path of a downloaded file that was saved to the SD card, but I'm running into troubles when I try to retrieve it. When I try to convert it to a Bitmap, it says the file can't be found, even though it is on the SD card.
File example : /storage/emulated/0/_1404876264453.jpeg
Here's the code that I use to download a photo, and store it to the SD card (returns the URL of where it is saved on the device):
private String downloadProfile(String url)
{
String imageUrl = null;
try
{
String PATH = Environment.getExternalStorageDirectory().getAbsolutePath();
String mimeType = getMimeType(url);
String fileExtension = "."+mimeType.replace("image/", "");
URL u = new URL(url);
HttpURLConnection con = (HttpURLConnection) u.openConnection();
con.setRequestMethod("GET");
con.setDoInput(true);
con.connect();
long millis=System.currentTimeMillis();
File file = new File(PATH);
file.mkdirs();
File outputFile = new File(file, "_"+millis);
FileOutputStream f = new FileOutputStream(outputFile);
InputStream in = con.getInputStream();
byte[] buffer = new byte[1024];
int len1 = 0;
while ((len1 = in.read()) > 0){
f.write(buffer, 0, len1);
}
imageUrl = outputFile.getAbsolutePath()+fileExtension;
f.close();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return imageUrl;
}
After downloading it, I insert the above URL into a SQLite database; it stores fine. I used Astro file manager to check if the file was there, and it was.
Here's the code in my BaseAdapter that takes the above file url and attemps to convert it into a Bitmap:
BitmapFactory.Options options = new BitmapFactory.Options();
options.inPreferredConfig = Bitmap.Config.ARGB_8888;
String profilePath = result_pos.get("profile_url"); // this just returns the example url
Bitmap bitmap = BitmapFactory.decodeFile(profilePath, options);
imageView.setImageBitmap(bitmap);
LogCat:
07-08 23:35:17.660: E/BitmapFactory(25463): Unable to decode stream: java.io.FileNotFoundException: /storage/emulated/0/_1404876264453.jpeg: open failed: ENOENT (No such file or directory)
check this link.i hope its useful to you.
reference link
1)create your own folder and save image name in proper way.
2)save image path in sqlite database
3)retrieve same path for get images.

How can I convert response json string image into a displayable image

My final year project requires me to develop a mobile application which fetches a number of Json values from a server. This is my first experience in android development but sure learned something’s and enjoyed the experience.
I have managed to develop the following.
1-a json parser class which fetches the value.
2-a class which displays these values.
3-a database where I store the json response.
However I'm one step away from completing my project, I cannot display the response string image address as real images (shame on me).
I need to do the following.
1- Parse the string path of the image and display the response as image.
I have spent most of my time trying to find the solution on the web, stack overflow. But no luck so far.
I need to do something like this in order to display these images together with the text descriptions.
I have now reached the cross roads and my knowledge has been tested.Is what i'm trying to do here posible?.
Who can show me the way? ,to this outstanding platform.
if you have the image url as a string, you can load and save the image using something like this:
try {
Bitmap bitmap = null;
File f = new File(filename);
InputStream inputStream = new URL(url).openStream();
OutputStream outputStream = new FileOutputStream(f);
int readlen;
byte[] buf = new byte[1024];
while ((readlen = inputStream.read(buf)) > 0)
outputStream.write(buf, 0, readlen);
outputStream.close();
inputStream.close();
bitmap = BitmapFactory.decodeFile(filename);
return bitmap;
} catch (Exception e) {
return null;
}
For saving, make sure you have appropriate permissions if you're going to save to sdcard.
if you just want to load the image (without saving):
Bitmap bm = null;
try {
URL aURL = new URL(url);
URLConnection conn = aURL.openConnection();
conn.connect();
InputStream is = conn.getInputStream();
BufferedInputStream bis = new BufferedInputStream(is);
bm = BitmapFactory.decodeStream(bis);
bis.close();
is.close();
} catch (IOException e) {
Log.e(TAG, "Error getting bitmap", e);
}
return bm;
Just make sure you fetch the image in a separate thread or using AsyncTask or else you'll get ANRs!
you can try this ImageDownloader class from google. It´s works nice :)
Is an AsynkTask that handle the download and set the bitmap to an ImageView.
ImageDownloader
Usage:
private final ImageDownloader mDownload = new ImageDownloader();
mDownload.download("URL", imageView);

Android : Getting this error while downloading image from remote server: SkImageDecoder::Factory returned null

I am trying to download images from a remote server, the number of images downloaded is 30. The code i am using to download image is as below. Some images download successfully and some images don't download and raises the above exception. What might be the problem.
public static Bitmap loadBitmap(String url)
{
Bitmap bitmap = null;
InputStream in = null;
BufferedOutputStream out = null;
try {
in = new BufferedInputStream(new URL(url).openStream(), 4*1024);
final ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
out = new BufferedOutputStream(dataStream, 4 * 1024);
int byte_;
while ((byte_ = in.read()) != -1)
out.write(byte_);
out.flush();
final byte[] data = dataStream.toByteArray();
BitmapFactory.Options options = new BitmapFactory.Options();
//options.inSampleSize = 1;
bitmap = BitmapFactory.decodeByteArray(data, 0, data.length,options);
} catch (IOException e) {
Log.e("","Could not load Bitmap from: " + url);
} finally {
try{
in.close();
out.close();
}catch( IOException e )
{
System.out.println(e);
}
}
return bitmap;
}
Please look on my this post
Image download code works for all image format, issues with PNG format rendering
In my case I solved this error with encode the url
Because image url that i wanted to download has the Persian letters(or other Unicode character) in it
So I replaced all Persian characters with encoded UTF-8 letters

Android: How to download a .png file using Async and set it to ImageView?

I've got the URL of a .png image, that needs to be downloaded and set as a source of an ImageView. I'm a beginner so far, so there are a few things I don't understand:
1) Where do I store the file?
2) How do I set it to the ImageView in java code?
3) How to correctly override the AsyncTask methods?
Thanks in advance, will highly appreciate any kind of help.
I'm not sure you can explicity build a png from a download. However, here is what I use to download images and display them into Imageviews :
First, you download the image :
protected static byte[] imageByter(Context ctx, String strurl) {
try {
URL url = new URL(urlContactIcon + strurl);
InputStream is = (InputStream) url.getContent();
byte[] buffer = new byte[8192];
int bytesRead;
ByteArrayOutputStream output = new ByteArrayOutputStream();
while ((bytesRead = is.read(buffer)) != -1) {
output.write(buffer, 0, bytesRead);
}
return output.toByteArray();
} catch (MalformedURLException e) {
e.printStackTrace();
return null;
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
And then, create a BitMap and associate it to the Imageview :
bytes = imagebyter(this, mUrl);
bm = BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
yourImageview.setImageBitmap(bm);
And that's it.
EDIT
Actually, you can save the file by doing this :
File file = new File(fileName);
FileOutputStream fos = new FileOutputStream(file);
fos.write(imagebyter(this, mUrl));
fos.close();
You can explicity build a png from a download.
bm.compress(Bitmap.CompressFormat.PNG, 100, out);
100 is your compression (PNG's are generally lossless so 100%)
out is your FileOutputStream to the file you want to save the png to.

Categories

Resources