I want to get bitmap from a inputstream, then re-size it. But I am getting below error.
If I return without re-sizing, it works fine.
Can anybody help please?
LOGCAT:
01-07 01:38:33.412: D/skia(1307): --- SkImageDecoder::Factory returned null
CODE:
private Bitmap getBitmap(String url)
{
try {
Bitmap bitmap=null;
URL imageUrl = new URL(url);
HttpURLConnection conn = (HttpURLConnection) imageUrl.openConnection();
conn.setConnectTimeout(10000);
conn.setReadTimeout(10000);
conn.setDoInput(true);
conn.setInstanceFollowRedirects(true);
conn.connect();
InputStream is=conn.getInputStream();
//return BitmapFactory.decodeStream(is); // THIS WORKS FINE
bitmap = decodeFile(is);
is.close();
return bitmap;
} catch (Exception ex){
return null;
}
}
private Bitmap decodeFile(InputStream istream){
BufferedInputStream is = new BufferedInputStream(istream);
try {
BitmapFactory.Options o = new BitmapFactory.Options();
o.inJustDecodeBounds = true;
BitmapFactory.decodeStream(is,null,o);
final int REQUIRED_SIZE=60;
int height_tmp=o.outHeight;
int scale=1;
while(true){
if(height_tmp/2<REQUIRED_SIZE)
break;
height_tmp/=2;
scale*=2;
}
BitmapFactory.Options o2 = new BitmapFactory.Options();
o2.inSampleSize=scale;
Log.d("insample", "aa: "+scale);
return BitmapFactory.decodeStream(is, null, o2);
} catch (Exception e) {
Log.d("aaa","aa: "+e);
} finally{
try {
is.close();
} catch( IOException ignored ) {}
}
return null;
}
at
iv.setImageResource(resId);
resId is invalid value...
change it to
iv.setImageResource(R.drawable.ic_launcher);
and test the code
Related
In short, I can't resize my image file (475px in height) using inSampleSize. Code as below.
Image should be reduced to 237.5 px, after the code, isn't it? But it remains unchanged, exactly same as original dimension.
Anybody can help please.
File f = new File(context.getCacheDir(), "1223fdf");
URL imageUrl = new URL("http://example.com/file.jpg");
HttpURLConnection conn = (HttpURLConnection)imageUrl.openConnection();
conn.setConnectTimeout(30000);
conn.setReadTimeout(30000);
conn.setInstanceFollowRedirects(false);
String url = conn.getHeaderField("Location");
URL redirectURL = new URL(url);
URLConnection redirectConn = redirectURL.openConnection();
InputStream is=redirectConn.getInputStream();
OutputStream os = new FileOutputStream(f);
Utils.CopyStream(is, os);
os.close();
BitmapFactory.Options o = new BitmapFactory.Options();
o.inJustDecodeBounds = true;
BitmapFactory.decodeStream(new FileInputStream(f),null,o);
final int REQUIRED_SIZE=200;
int height_tmp=o.outHeight; // This returns 475
int scale=1;
while(true){
if(height_tmp/2<REQUIRED_SIZE)
break;
height_tmp/=2;
scale*=2;
}
BitmapFactory.Options o2 = new BitmapFactory.Options();
o2.inSampleSize=scale; //SCALE = 2 here (checked by printing in LogCat)
Bitmap bmp = BitmapFactory.decodeStream(new FileInputStream(f), null, o2);
return bmp;
public class Utils {
public static void CopyStream(InputStream is, OutputStream os)
{
final int buffer_size=1024;
try
{
byte[] bytes=new byte[buffer_size];
for(;;)
{
int count=is.read(bytes, 0, buffer_size);
if(count==-1)
break;
os.write(bytes, 0, count);
}
}
catch(Exception ex){}
}
}
I return a Bitmap object according to a url, and the code for download picture:
URL url = new URL(imageUrlStr);
URLConnection conn = url.openConnection();
conn.setDoInput(true);
conn.connect();
InputStream in = conn.getInputStream();
Bitmap bitmap = BitmapFactory.decodeStream(in);
in.close
Then I save it to sdcard. It is ok to save picture.
Now the problem is it download the picture A when use this url to access. But it now shows another B picture in SDCARD. How to solve this problem?
You can identify images by hash-code. Not a perfect solution, good for the demo
private Bitmap getBitmap(String url) {
String filename = String.valueOf(url.hashCode());
File f = new File(cacheDir, filename);
// from SD cache
Bitmap b = decodeFile(f);
if (b != null)
return b;
// from web
try {
Bitmap bitmap = null;
InputStream is = new URL(url).openStream();
OutputStream os = new FileOutputStream(f);
CopyStream(is, os);
os.close();
bitmap = decodeFile(f);
return bitmap;
} catch (Exception ex) {
ex.printStackTrace();
return null;
}
}
private void CopyStream(InputStream is, OutputStream os) {
final int buffer_size = 1024;
try {
byte[] bytes = new byte[buffer_size];
for (;;) {
int count = is.read(bytes, 0, buffer_size);
if (count == -1)
break;
os.write(bytes, 0, count);
}
} catch (Exception ex) {
}
}
/** decodes image and scales it to reduce memory consumption*/
private Bitmap decodeFile(File f) {
try {
BitmapFactory.Options options = new BitmapFactory.Options();
options.inPurgeable = true;
return BitmapFactory.decodeStream(new FileInputStream(f));
} catch (FileNotFoundException e) {
}
return null;
}
Use you just need to use method "getBitmap(String)" with your desired url as String
I am trying to download images from URL. The image type is PNG and the resolution is 400x400 pixels.
Here is the download code snippet.
Bitmap bitmap=null;
URL imageUrl = new URL(url);
conn = (HttpURLConnection)imageUrl.openConnection();
conn.setConnectTimeout(30000);
conn.setReadTimeout(30000);
conn.setInstanceFollowRedirects(true);
InputStream ins=conn.getInputStream();
os = new FileOutputStream(f);
Utilities.getUtilities().copyStream(ins, os);
os.flush();
Log.i(TAG_NAME, "file size : "+ f.length());
Log.i(TAG_NAME, "file exists in cache? " + f.exists());
bitmap = decodeFile(f);
return bitmap;
Here is the file writer.
public void copyStream(InputStream is, OutputStream os) {
final int buffer_size=1024;
try
{
byte[] bytes=new byte[buffer_size];
for(;;)
{
int count=is.read(bytes, 0, buffer_size);
if(count==-1)
break;
os.write(bytes, 0, count);
}
}
catch(Exception ex){
ex.printStackTrace();
}
}
And the decode method
private Bitmap decodeFile(File f){
//decode image size
BitmapFactory.Options o = new BitmapFactory.Options();
o.inJustDecodeBounds = true;
try {
BitmapFactory.decodeStream(new FileInputStream(f));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
final int REQUIRED_SIZE = 400; //for testing, it is set to b a constant
System.out.println("REQUIRED_SIZE >>> " + REQUIRED_SIZE);
int width_tmp=o.outWidth, height_tmp=o.outHeight;
int scale=1;
while(true){
if(width_tmp/2<REQUIRED_SIZE || height_tmp/2<REQUIRED_SIZE)
break;
width_tmp/=2;
height_tmp/=2;
scale*=2;
}
//decode with inSampleSize
BitmapFactory.Options o2 = new BitmapFactory.Options();
//o2.inJustDecodeBounds = true;
o2.inPreferredConfig = Bitmap.Config.ARGB_8888;
o2.inSampleSize=scale; //scale is set off since android:src automatically scales the image to fit the screen
try {
return BitmapFactory.decodeStream(new FileInputStream(f));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
I can see that the file exists in the device. However, the decode stream is failing. I spent hours searching on the internet; tried almost everything, no success and almost my heads rolling.
Decode streams is causing the following error.
SkImageDecoder::Factory returned null
Do you find anything missing here?
EDIT:
Issue is now solved. The server was expecting cookie details which I failed to attach. Spent almost a day, beating around the bushes :-)
Thanks all for the valuable comments!
IMO, you may want to re-evaluate merits of httpurlconn vs native httpclient implementation. Android/google go for httpurlconn but, many opt to take greater control of low level details surrounding net protocol.
Here is sample async httpclient that wraps in bitmap handler. You can easily extend the sample method=processBitmapEntity() with your rules affecting bmp size.
Sample getbitmap url:
public int getBitmap(String mediaurl, int ctr){
Handler handler = new Handler() {
public void handleMessage(Message message) {
switch (message.what) {
case HttpConnection.DID_START: {
Log.d(TAG, "Starting connection...");
break;
}
case HttpConnection.DID_SUCCEED: {
//message obj is type bitmap
Log.d(TAG, "OK bmpARRAY " +message.arg1);
Bitmap response = (Bitmap) message.obj;
break;
}
case HttpConnection.DID_ERROR: {
Exception e = (Exception) message.obj;
e.printStackTrace();
Log.d(TAG, "Connection failed.");
break;
}
}
}
};
new HttpConnection(handler, PreferenceManager.getDefaultSharedPreferences(this), ctr).bitmap(mediaurl);
return -1;
And the bitmap handler in HttpConnection class that is part of the link sample above:
private void processBitmapEntity(HttpEntity entity) throws IOException {
BufferedHttpEntity bufHttpEntity = new BufferedHttpEntity(entity);
Bitmap bm = BitmapFactory.decodeStream(bufHttpEntity.getContent());
handler.sendMessage(Message.obtain(handler, DID_SUCCEED, bm));
}
And a git project
I have used:
InputStream in;
Bitmap bmp=BitmapFactory.decodeStream(in);
but the process waits for a long time and nothing happens. On the server side, i have the image converted into byte[].
I think this piece of code will be useful for you:
public Bitmap DownloadImage(String url)
{
HttpClient client = new DefaultHttpClient();
HttpResponse httpResponse;
Bitmap bmp = null;
try{
httpResponse = client.execute(new HttpGet(url));
responseCode = httpResponse.getStatusLine().getStatusCode();
HttpEntity entity = httpResponse.getEntity();
if (entity != null)
{
InputStream in = entity.getContent();
bmp = BitmapFactory.decodeStream(in);
in.close();
}
} catch (ClientProtocolException e) {
client.getConnectionManager().shutdown();
e.printStackTrace();
} catch (IOException e) {
client.getConnectionManager().shutdown();
e.printStackTrace();
}
return bmp;
}
Try this way to convert to bitmap.
try {
Bitmap bitmap=null;
URL imageUrl = new URL(url);
HttpURLConnection conn =
(HttpURLConnection)imageUrl.openConnection();
conn.setConnectTimeout(30000);
conn.setReadTimeout(30000);
conn.setInstanceFollowRedirects(true);
InputStream is=conn.getInputStream();
InputStream is;
OutputStream os = new FileOutputStream(f);
bitmap = decodeFile(f);
return bitmap;
} catch (Exception ex){
ex.printStackTrace();
return null;
}
// decodes image and scales it to reduce memory consumption
private Bitmap decodeFile(File f) {
try {
// decode image size
BitmapFactory.Options o = new BitmapFactory.Options();
o.inJustDecodeBounds = true;
BitmapFactory.decodeStream(new FileInputStream(f), null, o);
// Find the correct scale value. It should be the power of 2.
final int REQUIRED_SIZE = 70;
int width_tmp = o.outWidth, height_tmp = o.outHeight;
int scale = 1;
while (true) {
if (width_tmp / 2 < REQUIRED_SIZE
|| height_tmp / 2 < REQUIRED_SIZE)
break;
width_tmp /= 2;
height_tmp /= 2;
scale *= 2;
}
// decode with inSampleSize
BitmapFactory.Options o2 = new BitmapFactory.Options();
o2.inSampleSize = scale;
return BitmapFactory.decodeStream(new FileInputStream(f), null, o2);
} catch (FileNotFoundException e) {
}
return null;
}
I am using the code below in asyn task to download a bitmap to be added to my custom class. however sometimes it return nulls with no IOException or any exception. i am not very sure what can be done
public Bitmap downloadFile(String fileUrl){
URL myFileUrl =null;
try {
myFileUrl= new URL(fileUrl);
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
HttpURLConnection conn= (HttpURLConnection)myFileUrl.openConnection();
conn.setDoInput(true);
//conn.setReadTimeout(500000000);
conn.connect();
InputStream is = conn.getInputStream();
BitmapFactory.Options o = new BitmapFactory.Options();
o.inJustDecodeBounds = true;
BitmapFactory.decodeStream(is, null, o);
is.close();
conn.disconnect();
int scale = 1;
int IMAGE_MAX_SIZE=400;
if (o.outHeight > IMAGE_MAX_SIZE || o.outWidth > IMAGE_MAX_SIZE) {
scale = (int)Math.pow(2, (int) Math.round(Math.log(IMAGE_MAX_SIZE / (double) Math.max(o.outHeight, o.outWidth)) / Math.log(0.5)));
}
//Decode with inSampleSize
BitmapFactory.Options o2 = new BitmapFactory.Options();
o2.inSampleSize = scale;
conn= (HttpURLConnection)myFileUrl.openConnection();
conn.setDoInput(true);
//conn.setReadTimeout(500000000);
conn.connect();
is = conn.getInputStream();
Bitmap b = BitmapFactory.decodeStream(is, null, o2);
if (b==null)
Log.e(Config.log_id, " Download image failed");
return b;
}
catch (IOException e) {
Log.e(Config.log_id, " Download image failed"+e.getMessage());
e.printStackTrace();
}
return null;
}
I have run into this as well when using unbuffered variants of
stream readers when getting from urls.
The simple solution that worked for me was to use a BufferedHttpEntity to get the image data.
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.entity.BufferedHttpEntity;
public static Bitmap decodeFromUrl(HttpClient client, URL url, Config bitmapCOnfig)
{
HttpResponse response=null;
Bitmap b=null;
InputStream instream=null;
BitmapFactory.Options decodeOptions = new BitmapFactory.Options();
decodeOptions.inPreferredConfig = bitmapCOnfig;
try
{
HttpGet request = new HttpGet(url.toURI());
response = client.execute(request);
if (response.getStatusLine().getStatusCode() != 200)
{
MyLogger.w("Bad response on " + url.toString());
MyLogger.w ("http response: " + response.getStatusLine().toString());
return null;
}
BufferedHttpEntity bufHttpEntity = new BufferedHttpEntity(response.getEntity());
instream = bufHttpEntity.getContent();
return BitmapFactory.decodeStream(instream, null, decodeOptions);
}
catch (Exception ex)
{
MyLogger.e("error decoding bitmap from:" + url, ex);
if (response != null)
{
MyLogger.e("http status: " + response.getStatusLine().getStatusCode());
}
return null;
}
finally
{
if (instream != null)
{
try {
instream.close();
} catch (IOException e) {
MyLogger.e("error closing stream", e);
}
}
}
}