List of usage examples for android.graphics BitmapFactory decodeStream
@Nullable public static Bitmap decodeStream(@Nullable InputStream is, @Nullable Rect outPadding, @Nullable Options opts)
From source file:com.google.android.panoramio.BitmapUtilsTask.java
/** * Loads a bitmap from the specified url. * //from ww w . j av a2s .c o m * @param url The location of the bitmap asset * @return The bitmap, or null if it could not be loaded * @throws IOException * @throws MalformedURLException */ public Bitmap getBitmap(final String string, Object fileObj) throws MalformedURLException, IOException { File file = (File) fileObj; // Get the source image's dimensions int desiredWidth = 1000; BitmapFactory.Options options = new BitmapFactory.Options(); options.inJustDecodeBounds = true; if (!file.isFile()) { InputStream is = (InputStream) new URL(string).getContent(); BitmapFactory.decodeStream(is, null, options); is.close(); } else { BitmapFactory.decodeFile(file.getAbsolutePath(), options); } int srcWidth = options.outWidth; int srcHeight = options.outHeight; // Only scale if the source is big enough. This code is just trying // to fit a image into a certain width. if (desiredWidth > srcWidth) desiredWidth = srcWidth; // Calculate the correct inSampleSize/scale value. This helps reduce // memory use. It should be a power of 2 int inSampleSize = 1; while (srcWidth / 2 > desiredWidth) { srcWidth /= 2; srcHeight /= 2; inSampleSize *= 2; } // Decode with inSampleSize options.inJustDecodeBounds = false; options.inDither = false; options.inSampleSize = inSampleSize; options.inScaled = false; options.inPreferredConfig = Bitmap.Config.ARGB_8888; options.inPurgeable = true; Bitmap sampledSrcBitmap; if (!file.isFile()) { InputStream is = (InputStream) new URL(string).getContent(); sampledSrcBitmap = BitmapFactory.decodeStream(is, null, options); is.close(); } else { sampledSrcBitmap = BitmapFactory.decodeFile(file.getAbsolutePath(), options); } return sampledSrcBitmap; }
From source file:com.onemorecastle.util.HttpFetch.java
public static Bitmap fetchBitmap(String imageAddress, int sampleSize) throws MalformedURLException, IOException { Bitmap bitmap = null;//from www .jav a2 s . c om DefaultHttpClient httpclient = null; try { HttpParams httpParameters = new BasicHttpParams(); HttpConnectionParams.setConnectionTimeout(httpParameters, 2000); HttpConnectionParams.setSoTimeout(httpParameters, 5000); HttpConnectionParams.setSocketBufferSize(httpParameters, 512); HttpGet httpRequest = new HttpGet(URI.create(imageAddress)); httpclient = new DefaultHttpClient(); httpclient.setParams(httpParameters); HttpResponse response = (HttpResponse) httpclient.execute(httpRequest); HttpEntity entity = response.getEntity(); BufferedHttpEntity bufHttpEntity = new BufferedHttpEntity(entity); InputStream instream = bufHttpEntity.getContent(); BitmapFactory.Options options = new BitmapFactory.Options(); //first decode with inJustDecodeBounds=true to check dimensions options.inJustDecodeBounds = true; options.inSampleSize = sampleSize; BitmapFactory.decodeStream(instream, null, options); //decode bitmap with inSampleSize set options.inSampleSize = calculateInSampleSize(options, MAX_WIDTH, MAX_HEIGHT); options.inPurgeable = true; options.inInputShareable = true; options.inDither = true; options.inJustDecodeBounds = false; //response=(HttpResponse)httpclient.execute(httpRequest); //entity=response.getEntity(); //bufHttpEntity=new BufferedHttpEntity(entity); instream = bufHttpEntity.getContent(); bitmap = BitmapFactory.decodeStream(instream, null, options); //close out stuff try { instream.close(); bufHttpEntity.consumeContent(); entity.consumeContent(); } finally { instream = null; bufHttpEntity = null; entity = null; } } catch (Exception x) { Log.e("HttpFetch.fetchBitmap", imageAddress, x); } finally { httpclient = null; } return (bitmap); }
From source file:com.madrobot.tasks.DownloadBitmapTask.java
@Override protected Object doInBackground(Object... params) { /*sending*///ww w . ja v a 2 s . c om taskStarted(); URI[] uri = (URI[]) params[0]; BitmapFactory.Options opt = (Options) params[1]; for (int i = 0; i < uri.length; i++) { DataResponse response = new DataResponse(); response.setResponseId(i); HttpTaskHelper helper = new HttpTaskHelper(uri[i]); try { Log.d("BitmapTask", "Downloading Bitmap->" + uri[i]); HttpEntity entity = helper.execute(); InputStream is = entity.getContent(); Bitmap bitmap = BitmapFactory.decodeStream(is, null, opt); response.setData(bitmap); response.setResponseStatus(1); Log.d("BitmapTask", "Complete!"); publishProgress(response); } catch (IOException e) { response.setResponseStatus(-1); response.setT(e); e.printStackTrace(); } catch (URISyntaxException e) { response.setResponseStatus(-1); response.setT(e); e.printStackTrace(); } } return null; }
From source file:Main.java
/** * Decode downloaded big picture.//from w ww. j a va 2 s.c o m * @param context any application context. * @param downloadId downloaded picture identifier. * @return decoded bitmap if successful, null on error. */ public static Bitmap getBigPicture(Context context, long downloadId) { /* Decode bitmap */ InputStream stream = null; try { /* * Query download manager to get file. FIXME For an unknown reason, using the file descriptor * fails after APK build with ProGuard, we use stream instead. */ DownloadManager downloadManager = (DownloadManager) context.getSystemService(Context.DOWNLOAD_SERVICE); Uri uri = downloadManager.getUriForDownloadedFile(downloadId); ContentResolver contentResolver = context.getContentResolver(); stream = contentResolver.openInputStream(uri); /* * Bitmaps larger than 2048 in any dimension are likely to cause OutOfMemoryError in the * NotificationManager or even here. Plus some devices simply don't accept such images: the * notification manager can drop the notification without any way to check that via API. To * avoid the problem, sub sample the image in an efficient way (not using Bitmap matrix * scaling after decoding the bitmap with original size: it could run out of memory when * decoding the full image). FIXME There is center cropping applied by the NotificationManager * on the bitmap we provide, we can't avoid it, see * https://code.google.com/p/android/issues/detail?id=58318. */ BitmapFactory.Options options = new BitmapFactory.Options(); options.inJustDecodeBounds = true; options.inSampleSize = 1; options.inPreferQualityOverSpeed = true; /* Decode dimensions */ BitmapFactory.decodeStream(stream, null, options); int maxDim = Math.max(options.outWidth, options.outHeight); /* Compute sub sample size (it must be a power of 2) */ while (maxDim > 2048) { options.inSampleSize <<= 1; maxDim >>= 1; } /* Decode actual bitmap */ options.inJustDecodeBounds = false; stream.close(); stream = contentResolver.openInputStream(uri); return BitmapFactory.decodeStream(stream, null, options); } catch (Throwable t) { /* Abort, causes are likely FileNotFoundException or OutOfMemoryError */ return null; } finally { /* Silently close stream */ if (stream != null) try { stream.close(); } catch (IOException e) { } } }
From source file:com.wishlist.Utility.java
public static byte[] scaleImage(Context context, Uri photoUri) throws IOException { InputStream is = context.getContentResolver().openInputStream(photoUri); BitmapFactory.Options dbo = new BitmapFactory.Options(); dbo.inJustDecodeBounds = true;//from ww w . j av a 2 s . com BitmapFactory.decodeStream(is, null, dbo); is.close(); int rotatedWidth, rotatedHeight; int orientation = getOrientation(context, photoUri); if (orientation == 90 || orientation == 270) { rotatedWidth = dbo.outHeight; rotatedHeight = dbo.outWidth; } else { rotatedWidth = dbo.outWidth; rotatedHeight = dbo.outHeight; } Bitmap srcBitmap; is = context.getContentResolver().openInputStream(photoUri); if (rotatedWidth > MAX_IMAGE_DIMENSION || rotatedHeight > MAX_IMAGE_DIMENSION) { float widthRatio = ((float) rotatedWidth) / ((float) MAX_IMAGE_DIMENSION); float heightRatio = ((float) rotatedHeight) / ((float) MAX_IMAGE_DIMENSION); float maxRatio = Math.max(widthRatio, heightRatio); // Create the bitmap from file BitmapFactory.Options options = new BitmapFactory.Options(); options.inSampleSize = (int) maxRatio; srcBitmap = BitmapFactory.decodeStream(is, null, options); } else { srcBitmap = BitmapFactory.decodeStream(is); } is.close(); /* if the orientation is not 0 (or -1, which means we don't know), we * have to do a rotation. */ if (orientation > 0) { Matrix matrix = new Matrix(); matrix.postRotate(orientation); srcBitmap = Bitmap.createBitmap(srcBitmap, 0, 0, srcBitmap.getWidth(), srcBitmap.getHeight(), matrix, true); } String type = context.getContentResolver().getType(photoUri); ByteArrayOutputStream baos = new ByteArrayOutputStream(); if (type.equals("image/png")) { srcBitmap.compress(Bitmap.CompressFormat.PNG, 100, baos); } else if (type.equals("image/jpg") || type.equals("image/jpeg")) { srcBitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos); } byte[] bMapArray = baos.toByteArray(); baos.close(); return bMapArray; }
From source file:com.ibuildapp.romanblack.CataloguePlugin.imageloader.Utils.java
public static Bitmap processBitmap(String fileName, Bitmap.Config config, int widthLimit) { Bitmap bitmap = null;/*from w ww . jav a2s.c o m*/ try { File tempFile = new File(fileName); BitmapFactory.Options opts = new BitmapFactory.Options(); BufferedInputStream fileInputStream = new BufferedInputStream(new FileInputStream(tempFile)); opts.inJustDecodeBounds = true; BitmapFactory.decodeStream(fileInputStream, null, opts); fileInputStream.close(); fileInputStream = new BufferedInputStream(new FileInputStream(tempFile)); //Find the correct scale value. It should be the power of 2. int width = opts.outWidth; int scale = 1; while (true) { int halfWidth = width / 2; if (halfWidth < widthLimit && (widthLimit - halfWidth) > widthLimit / 4) break; width = halfWidth; scale *= 2; } opts = new BitmapFactory.Options(); opts.inSampleSize = scale; opts.inPreferredConfig = config; try { System.gc(); bitmap = BitmapFactory.decodeStream(fileInputStream, null, opts); if (bitmap != null) return bitmap; } catch (Exception ex) { } catch (OutOfMemoryError e) { } fileInputStream.close(); fileInputStream = new BufferedInputStream(new FileInputStream(tempFile)); try { Thread.sleep(300); } catch (InterruptedException e) { e.printStackTrace(); } try { System.gc(); bitmap = BitmapFactory.decodeStream(fileInputStream, null, opts); if (bitmap != null) return bitmap; } catch (Exception ex) { } catch (OutOfMemoryError ex) { } fileInputStream.close(); fileInputStream = new BufferedInputStream(new FileInputStream(tempFile)); try { Thread.sleep(300); } catch (InterruptedException e) { e.printStackTrace(); } try { System.gc(); bitmap = BitmapFactory.decodeStream(fileInputStream, null, opts); } catch (Exception ex) { } catch (OutOfMemoryError ex) { } fileInputStream.close(); } catch (Exception exception) { exception.printStackTrace(); } return bitmap; }
From source file:com.example.facebook_photo.Utility.java
public static byte[] scaleImage(Context context, Uri photoUri) throws IOException { InputStream is = context.getContentResolver().openInputStream(photoUri); BitmapFactory.Options dbo = new BitmapFactory.Options(); dbo.inJustDecodeBounds = true;/*w w w. ja va2s .co m*/ BitmapFactory.decodeStream(is, null, dbo); is.close(); int rotatedWidth, rotatedHeight; int orientation = getOrientation(context, photoUri); if (orientation == 90 || orientation == 270) { rotatedWidth = dbo.outHeight; rotatedHeight = dbo.outWidth; } else { rotatedWidth = dbo.outWidth; rotatedHeight = dbo.outHeight; } Bitmap srcBitmap; is = context.getContentResolver().openInputStream(photoUri); if (rotatedWidth > MAX_IMAGE_DIMENSION || rotatedHeight > MAX_IMAGE_DIMENSION) { float widthRatio = ((float) rotatedWidth) / ((float) MAX_IMAGE_DIMENSION); float heightRatio = ((float) rotatedHeight) / ((float) MAX_IMAGE_DIMENSION); float maxRatio = Math.max(widthRatio, heightRatio); // Create the bitmap from file BitmapFactory.Options options = new BitmapFactory.Options(); options.inSampleSize = (int) maxRatio; srcBitmap = BitmapFactory.decodeStream(is, null, options); } else { srcBitmap = BitmapFactory.decodeStream(is); } is.close(); /* * if the orientation is not 0 (or -1, which means we don't know), we * have to do a rotation. */ if (orientation > 0) { Matrix matrix = new Matrix(); matrix.postRotate(orientation); srcBitmap = Bitmap.createBitmap(srcBitmap, 0, 0, srcBitmap.getWidth(), srcBitmap.getHeight(), matrix, true); } String type = context.getContentResolver().getType(photoUri); ByteArrayOutputStream baos = new ByteArrayOutputStream(); if (type.equals("image/png")) { srcBitmap.compress(Bitmap.CompressFormat.PNG, 100, baos); } else if (type.equals("image/jpg") || type.equals("image/jpeg")) { srcBitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos); } byte[] bMapArray = baos.toByteArray(); baos.close(); return bMapArray; }
From source file:com.cooliris.media.UriTexture.java
private static int computeSampleSize(InputStream stream, int maxResolutionX, int maxResolutionY) { BitmapFactory.Options options = new BitmapFactory.Options(); options.inJustDecodeBounds = true;//www . j ava2 s . c om BitmapFactory.decodeStream(stream, null, options); double w = options.outWidth; double h = options.outHeight; int sampleSize = (int) Math.ceil(Math.max(w / maxResolutionX, h / maxResolutionY)); return sampleSize; }
From source file:com.android.browser.kai.DownloadTouchIcon.java
@Override public Bitmap doInBackground(String... values) { String url = values[0];//from w w w . jav a 2 s . co m AndroidHttpClient client = AndroidHttpClient.newInstance(mUserAgent); HttpGet request = new HttpGet(url); // Follow redirects HttpClientParams.setRedirecting(client.getParams(), true); try { HttpResponse response = client.execute(request); if (response.getStatusLine().getStatusCode() == 200) { HttpEntity entity = response.getEntity(); if (entity != null) { InputStream content = entity.getContent(); if (content != null) { Bitmap icon = BitmapFactory.decodeStream(content, null, null); return icon; } } } } catch (IllegalArgumentException ex) { request.abort(); } catch (IOException ex) { request.abort(); } finally { client.close(); } return null; }
From source file:edu.stanford.mobisocial.dungbeetle.feed.objects.PictureObj.java
public static DbObject from(Context context, Uri imageUri) throws IOException { // Query gallery for camera picture via // Android ContentResolver interface ContentResolver cr = context.getContentResolver(); BitmapFactory.Options options = new BitmapFactory.Options(); options.inJustDecodeBounds = true;//from w w w. j a va2 s .c om BitmapFactory.decodeStream(cr.openInputStream(imageUri), null, options); int targetSize = 200; int xScale = (options.outWidth + targetSize - 1) / targetSize; int yScale = (options.outHeight + targetSize - 1) / targetSize; int scale = xScale < yScale ? xScale : yScale; //uncomment this to get faster power of two scaling //for(int i = 0; i < 32; ++i) { // int mushed = scale & ~(1 << i); // if(mushed != 0) // scale = mushed; //} options.inJustDecodeBounds = false; options.inSampleSize = scale; Bitmap sourceBitmap = BitmapFactory.decodeStream(cr.openInputStream(imageUri), null, options); int width = sourceBitmap.getWidth(); int height = sourceBitmap.getHeight(); int cropSize = Math.min(width, height); float scaleSize = ((float) targetSize) / cropSize; Matrix matrix = new Matrix(); matrix.postScale(scaleSize, scaleSize); float rotation = PhotoTaker.rotationForImage(context, imageUri); if (rotation != 0f) { matrix.preRotate(rotation); } Bitmap resizedBitmap = Bitmap.createBitmap(sourceBitmap, 0, 0, width, height, matrix, true); ByteArrayOutputStream baos = new ByteArrayOutputStream(); resizedBitmap.compress(Bitmap.CompressFormat.JPEG, 90, baos); byte[] data = baos.toByteArray(); sourceBitmap.recycle(); sourceBitmap = null; resizedBitmap.recycle(); resizedBitmap = null; System.gc(); // TODO: gross. JSONObject base = new JSONObject(); if (ContentCorral.CONTENT_CORRAL_ENABLED) { try { String type = cr.getType(imageUri); if (type == null) { type = "image/jpeg"; } base.put(CorralClient.OBJ_LOCAL_URI, imageUri.toString()); base.put(CorralClient.OBJ_MIME_TYPE, type); String localIp = ContentCorral.getLocalIpAddress(); if (localIp != null) { base.put(Contact.ATTR_LAN_IP, localIp); } } catch (JSONException e) { Log.e(TAG, "impossible json error possible!"); } } return from(base, data); }