Mega Code Archive

 
Categories / Android / 2D Graphics
 

Get Drawable From Web Operation

//package com.filmatchs.utils; import java.io.ByteArrayOutputStream; import java.io.InputStream; import java.net.URL; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.drawable.Drawable; import android.util.Log; /**  * TODO: class ini harus dikembangkan menjadi  *   * @author khalifavi  *   */ public class ImageManager {   public static final String LOG_TAG = "DrawableManager";   /**    * get Drawable from a URL request    * @param url    * @return Drawable    */   public static Drawable getDrawableFromWebOperation(String url) {     try {       InputStream is = (InputStream) new URL(url).getContent();       Drawable d = Drawable.createFromStream(is, url);       return d;     } catch (Exception e) {       Log.e(LOG_TAG, e.getMessage());       return null;     }   }   /**    * get Bitmap from a URL request    * @param url    * @return Bitmap    */   public static Bitmap getBitmapFromWebOperation(String url) {     try {       InputStream is = (InputStream) new URL(url).getContent();       Bitmap b = BitmapFactory.decodeStream(is);       return b;     } catch (Exception e) {       Log.e(LOG_TAG, e.getMessage());       return null;     }   }   /**    * get ByteArray from a URL request     * @param url    * @return ByteArray    */   public static byte[] getByteArrayFromWebOperation(String url) {     try {       InputStream is = (InputStream) new URL(url).getContent();       // this dynamically extends to take the bytes you read       ByteArrayOutputStream byteBuffer = new ByteArrayOutputStream();       // this is storage overwritten on each iteration with bytes       byte[] buffer = new byte[1024];       // we need to know how may bytes were read to write them to the       // byteBuffer       int len = 0;       while ((len = is.read(buffer)) != -1) {         byteBuffer.write(buffer, 0, len);       }       // and then we can return your byte array.       return byteBuffer.toByteArray();     } catch (Exception e) {       Log.e(LOG_TAG, e.getMessage());       return null;     }   }   /**    * Resize a Bitmap    * @param bitmap    * @param width    * @param height    * @return Bitmap resized bitmap    */   public static Bitmap getResizedBitmap(Bitmap bitmap, int width, int height) {     final int bitmapWidth = bitmap.getWidth();     final int bitmapHeight = bitmap.getHeight();     final float scale = Math.min((float) width / (float) bitmapWidth,         (float) height / (float) bitmapHeight);     final int scaledWidth = (int) (bitmapWidth * scale);     final int scaledHeight = (int) (bitmapHeight * scale);     final Bitmap decored = Bitmap.createScaledBitmap(bitmap, scaledWidth,         scaledHeight, true);     return decored;   } }