Android Image Getter for Larger Images

断了今生、忘了曾经 提交于 2020-01-01 18:59:06

问题


I have used all the Standard Network related code for Getting Images of about 45KB to 75KB but all are failing these methods work fine for Files of about 3-5KB size of Images. How can I achieve Downloading Image of 45 - 75KB for displaying them on an ImageView in Android for my Network Operations the Things I have used are

final URL url = new URL(urlString);

final URLConnection conn = url.openConnection();
HttpURLConnection httpConn = (HttpURLConnection) conn;

httpConn.setAllowUserInteraction(true);

httpConn.setInstanceFollowRedirects(true);

httpConn.setRequestMethod("GET");

httpConn.connect();

and the Second option that I have had used is::

DefaultHttpClient httpClient = new DefaultHttpClient();

HttpGet getRequest = new HttpGet(urlString);

HttpResponse response = httpClient.execute(getRequest);

why is this code functional for Smaller Sized Images and not for Larger Size Images. ?


回答1:


It would be nice to see what kind of code you use for decoding the response into a bitmap. Anyway, try using a BufferedInputStream like this:

public Bitmap getRemoteImage(final URL aURL) { 
  try { 
    final URLConnection conn = aURL.openConnection(); 
    conn.connect(); 
    final BufferedInputStream bis = new BufferedInputStream(conn.getInputStream()); 
    final Bitmap bm = BitmapFactory.decodeStream(bis); 
    return bm; 
  } catch (IOException e) { 
    Log.d("DEBUGTAG", "Oh noooz an error..."); 
  } 
  return null; 
}



回答2:


The size of the image you are downloading is pretty irrelevant. The size it decodes with BitmapFactory.decodeStream, however is the memory you are going to need to handle the image. Therefore a reSampling might be useful.

    Options options = new BitmapFactory.Options();
    options.inJustDecodeBounds = true;

    BitmapFactory.decodeStream(is, null, options);

    Boolean scaleByHeight = Math.abs(options.outHeight - TARGET_HEIGHT) >= Math.abs(options.outWidth - TARGET_WIDTH);

    if(options.outHeight * options.outWidth >= 200*200){
    // Load, scaling to smallest power of 2 if dimensions >= desired dimensions
    double sampleSize = scaleByHeight
            ? options.outHeight / TARGET_HEIGHT
            : options.outWidth / TARGET_WIDTH;
    options.inSampleSize = 
          (int)Math.pow(2d, Math.floor(
          Math.log(sampleSize)/Math.log(2d)));
    }

    // Do the actual decoding
    options.inJustDecodeBounds = false;

    is.close();
    is = getHTTPConnectionInputStream(sUrl);
    Bitmap img = BitmapFactory.decodeStream(is, null, options);
    is.close();


来源:https://stackoverflow.com/questions/2494396/android-image-getter-for-larger-images

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!