Monday, 21 October 2013

Sampling of images return null.....resolve by me

Bitmap bitmap=null;
         URL imageUrl = new URL(url);  //url from where you want to fetch data
         System.out.println(imageUrl);
         HttpURLConnection conn = (HttpURLConnection)imageUrl.openConnection();
         conn.setConnectTimeout(30000);
         conn.setReadTimeout(30000);
         conn.setInstanceFollowRedirects(true);
         InputStream is=conn.getInputStream();
     

 ByteArrayOutputStream baos = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024];
        int len;
        while ((len = is.read(buffer)) > -1 ) {
            baos.write(buffer, 0, len);
        }
        baos.flush();

        // Open new InputStreams using the recorded bytes
        // Can be repeated as many times as you wish
        InputStream is1 = new ByteArrayInputStream(baos.toByteArray());
        InputStream is2 = new ByteArrayInputStream(baos.toByteArray());

       

         BitmapFactory.Options o = new BitmapFactory.Options();
         o.inJustDecodeBounds = true;
     
 BitmapFactory.decodeStream(is1,null,o);

         //Decode with inSampleSize
     
         int sampleSize = calculateInSampleSize(o,200, 200);
     
         System.out.println();
         o.inSampleSize=sampleSize;
         o.inJustDecodeBounds = false;
     
   
       
      bitmap=BitmapFactory.decodeStream(is2,null,o);
      System.out.println(bitmap);
     is.close();
 


The function for calculate sample factor  is

public static int calculateInSampleSize(
            BitmapFactory.Options options, int reqWidth, int reqHeight) {
   final int height = options.outHeight;
   final int width = options.outWidth;
   int inSampleSize = 1;

   if (height > reqHeight || width > reqWidth) {

       final int heightRatio = Math.round((float) height / (float) reqHeight);
       final int widthRatio = Math.round((float) width / (float) reqWidth);

       inSampleSize = heightRatio < widthRatio ? heightRatio : widthRatio;
   }

   return inSampleSize;
}




No comments:

Post a Comment