List of usage examples for android.graphics BitmapFactory decodeFile
public static Bitmap decodeFile(String pathName, Options opts)
From source file:com.thejoshwa.ultrasonic.androidapp.util.Util.java
public static Bitmap decodeSampledBitmapFromFile(String path, int reqWidth, int reqHeight) { // First decode with inJustDecodeBounds=true to check dimensions final BitmapFactory.Options options = new BitmapFactory.Options(); options.inJustDecodeBounds = true;//from w ww. j av a2 s . co m BitmapFactory.decodeFile(path, options); // Calculate inSampleSize options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight); // Decode bitmap with inSampleSize set options.inJustDecodeBounds = false; return BitmapFactory.decodeFile(path, options); }
From source file:com.eleybourn.bookcatalogue.utils.Utils.java
/** * Shrinks the passed image file spec into the specificed dimensions, and returns the bitmap. If the view * is non-null, the image is also placed in the view. * /* w w w . j av a2 s. c o m*/ * @param destView * @param filename * @param maxWidth * @param maxHeight * @param exact * * @return */ private static Bitmap shrinkFileIntoImageView(ImageView destView, String filename, int maxWidth, int maxHeight, boolean exact) { Bitmap bm = null; // Read the file to get file size BitmapFactory.Options opt = new BitmapFactory.Options(); opt.inJustDecodeBounds = true; BitmapFactory.decodeFile(filename, opt); // If no size info, or a single pixel, assume file bad and set the 'alert' icon if (opt.outHeight <= 0 || opt.outWidth <= 0 || (opt.outHeight == 1 && opt.outWidth == 1)) { if (destView != null) destView.setImageResource(android.R.drawable.ic_dialog_alert); return null; } // Next time we don't just want the bounds, we want the file opt.inJustDecodeBounds = false; // Work out how to scale the file to fit in required bbox float widthRatio = (float) maxWidth / opt.outWidth; float heightRatio = (float) maxHeight / opt.outHeight; // Work out scale so that it fit exactly float ratio = widthRatio < heightRatio ? widthRatio : heightRatio; // Note that inSampleSize seems to ALWAYS be forced to a power of 2, no matter what we // specify, so we just work with powers of 2. int idealSampleSize = (int) android.util.FloatMath.ceil(1 / ratio); // This is the sample size we want to use // Get the nearest *bigger* power of 2. int samplePow2 = (int) Math.pow(2, Math.ceil(Math.log(idealSampleSize) / Math.log(2))); try { if (exact) { // Create one bigger than needed and scale it; this is an attempt to improve quality. opt.inSampleSize = samplePow2 / 2; if (opt.inSampleSize < 1) opt.inSampleSize = 1; Bitmap tmpBm = BitmapFactory.decodeFile(filename, opt); if (tmpBm == null) { // We ran out of memory, most likely // TODO: Need a way to try loading images after GC(), or something. Otherwise, covers in cover browser wil stay blank. Logger.logError( new RuntimeException("Unexpectedly failed to decode bitmap; memory exhausted?")); return null; } android.graphics.Matrix matrix = new android.graphics.Matrix(); // Fixup ratio based on new sample size and scale it. ratio = ratio / (1.0f / opt.inSampleSize); matrix.postScale(ratio, ratio); bm = Bitmap.createBitmap(tmpBm, 0, 0, opt.outWidth, opt.outHeight, matrix, true); // Recycle if original was not returned if (bm != tmpBm) { tmpBm.recycle(); tmpBm = null; } } else { // Use a scale that will make image *no larger than* the desired size if (ratio < 1.0f) opt.inSampleSize = samplePow2; bm = BitmapFactory.decodeFile(filename, opt); } } catch (OutOfMemoryError e) { return null; } // Set ImageView and return bitmap if (destView != null) destView.setImageBitmap(bm); return bm; }
From source file:de.vanita5.twittnuker.util.Utils.java
public static boolean downscaleImageIfNeeded(final File imageFile, final int quality) { if (imageFile == null || !imageFile.isFile()) return false; final String path = imageFile.getAbsolutePath(); final BitmapFactory.Options o = new BitmapFactory.Options(); o.inJustDecodeBounds = true;/*from w w w .j a va 2s . c o m*/ BitmapFactory.decodeFile(path, o); // Corrupted image, so return now. if (o.outWidth <= 0 || o.outHeight <= 0) return false; o.inJustDecodeBounds = false; if (o.outWidth > TWITTER_MAX_IMAGE_WIDTH || o.outHeight > TWITTER_MAX_IMAGE_HEIGHT) { // The image dimension is larger than Twitter's limit. o.inSampleSize = calculateInSampleSize(o.outWidth, o.outHeight, TWITTER_MAX_IMAGE_WIDTH, TWITTER_MAX_IMAGE_HEIGHT); try { final Bitmap b = BitmapDecodeHelper.decode(path, o); final Bitmap.CompressFormat format = getBitmapCompressFormatByMimetype(o.outMimeType, Bitmap.CompressFormat.PNG); final FileOutputStream fos = new FileOutputStream(imageFile); return b.compress(format, quality, fos); } catch (final OutOfMemoryError e) { return false; } catch (final FileNotFoundException e) { // This shouldn't happen. } catch (final IllegalArgumentException e) { return false; } } else if (imageFile.length() > TWITTER_MAX_IMAGE_SIZE) { // The file size is larger than Twitter's limit. try { final Bitmap b = BitmapDecodeHelper.decode(path, o); final FileOutputStream fos = new FileOutputStream(imageFile); return b.compress(Bitmap.CompressFormat.JPEG, 80, fos); } catch (final OutOfMemoryError e) { return false; } catch (final FileNotFoundException e) { // This shouldn't happen. } } return true; }
From source file:com.nttec.everychan.ui.gallery.GalleryActivity.java
private void setWebView(final GalleryItemViewTag tag, final File file) { runOnUiThread(new Runnable() { private boolean oomFlag = false; private final ViewGroup.LayoutParams MATCH_PARAMS = new ViewGroup.LayoutParams( ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT); private void prepareWebView(WebView webView) { webView.setBackgroundColor(Color.TRANSPARENT); webView.setInitialScale(100); webView.setScrollBarStyle(WebView.SCROLLBARS_OUTSIDE_OVERLAY); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ECLAIR) { CompatibilityImpl.setScrollbarFadingEnabled(webView, true); }//from w ww . j ava 2 s . c om WebSettings settings = webView.getSettings(); settings.setBuiltInZoomControls(true); settings.setSupportZoom(true); settings.setAllowFileAccess(true); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ECLAIR_MR1) { CompatibilityImpl.setDefaultZoomFAR(settings); CompatibilityImpl.setLoadWithOverviewMode(settings, true); } settings.setUseWideViewPort(true); settings.setCacheMode(WebSettings.LOAD_NO_CACHE); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.FROYO) { CompatibilityImpl.setBlockNetworkLoads(settings, true); } setScaleWebView(webView); } private void setScaleWebView(final WebView webView) { Runnable callSetScaleWebView = new Runnable() { @Override public void run() { setPrivateScaleWebView(webView); } }; Point resolution = new Point(tag.layout.getWidth(), tag.layout.getHeight()); if (resolution.equals(0, 0)) { // wait until the view is measured and its size is known AppearanceUtils.callWhenLoaded(tag.layout, callSetScaleWebView); } else { callSetScaleWebView.run(); } } private void setPrivateScaleWebView(WebView webView) { Point imageSize = getImageSize(file); Point resolution = new Point(tag.layout.getWidth(), tag.layout.getHeight()); //Logger.d(TAG, "Resolution: "+resolution.x+"x"+resolution.y); double scaleX = (double) resolution.x / (double) imageSize.x; double scaleY = (double) resolution.y / (double) imageSize.y; int scale = (int) Math.round(Math.min(scaleX, scaleY) * 100d); scale = Math.max(scale, 1); //Logger.d(TAG, "Scale: "+(Math.min(scaleX, scaleY) * 100d)); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ECLAIR_MR1) { double picdpi = (getResources().getDisplayMetrics().density * 160d) / scaleX; if (picdpi >= 240) { CompatibilityImpl.setDefaultZoomFAR(webView.getSettings()); } else if (picdpi <= 120) { CompatibilityImpl.setDefaultZoomCLOSE(webView.getSettings()); } else { CompatibilityImpl.setDefaultZoomMEDIUM(webView.getSettings()); } } webView.setInitialScale(scale); webView.setPadding(0, 0, 0, 0); } private Point getImageSize(File file) { BitmapFactory.Options options = new BitmapFactory.Options(); options.inJustDecodeBounds = true; BitmapFactory.decodeFile(file.getAbsolutePath(), options); return new Point(options.outWidth, options.outHeight); } private boolean useFallback(File file) { String path = file.getPath().toLowerCase(Locale.US); if (path.endsWith(".png")) return false; if (path.endsWith(".jpg")) return false; if (path.endsWith(".gif")) return false; if (path.endsWith(".jpeg")) return false; if (path.endsWith(".webp") && Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) return false; return true; } @Override public void run() { try { recycleTag(tag, false); WebView webView = new WebViewFixed(GalleryActivity.this); webView.setLayoutParams(MATCH_PARAMS); tag.layout.addView(webView); if (settings.fallbackWebView() || useFallback(file)) { prepareWebView(webView); webView.loadUrl(Uri.fromFile(file).toString()); } else { JSWebView.setImage(webView, file); } tag.thumbnailView.setVisibility(View.GONE); tag.loadingView.setVisibility(View.GONE); tag.layout.setVisibility(View.VISIBLE); } catch (OutOfMemoryError oom) { System.gc(); Logger.e(TAG, oom); if (!oomFlag) { oomFlag = true; run(); } else showError(tag, getString(R.string.error_out_of_memory)); } } }); }
From source file:com.lifehackinnovations.siteaudit.FloorPlanActivity.java
public void save() { try {/*from w ww. ja va 2 s . c o m*/ runOnUiThread(new Runnable() { public void run() { view.addvaluestotabstable(); view.addvaluestobom(); if (u.isbluestacks()) { //Tabs1.bluestacksimagequalitydialog(getBaseContext()); } } }); if (ACTION == ACTION_SHOWLAYERS) { ACTION = ACTION_DONOTHING; } Log.d("MULTILEVEL checked in save", String.valueOf(MULTILEVEL)); // if(!MULTILEVEL){ // Canvas canvascopy = new Canvas(); // Bitmap canvasbitmap=resizedbitmaponmemorycheck(); // canvascopy.setBitmap(canvasbitmap); // // view.DONTSCALEORTRANSLATE = true; // view.CanvasChanges(canvascopy); // view.DONTSCALEORTRANSLATE = false; // // File file = new File(Tabs1.OutputFloorPlanLocation[FloorPlanView.fp]); // file.mkdirs(); // if (file.exists()) // file.delete(); // // FileOutputStream fos = new FileOutputStream( // new File(Tabs1.OutputFloorPlanLocation[FloorPlanView.fp])); // // canvasbitmap.compress(Bitmap.CompressFormat.PNG, 100, fos); // //canvasbitmap.recycle(); // try { // Log.d("trying outputstream flush and close","true"); // fos.flush(); // fos.close(); // fos = null; // } catch (IOException e) { // // TODO Auto-generated catch block // e.printStackTrace(); // } // }else{ //recycling original canvas Log.d("floorplancount", u.s(floorplancount)); for (int x = 0; x < floorplancount; x++) { Log.d("floorplan count", u.s(x)); FloorPlanView.fp = x; // view.originalbitmap = BitmapFactory.decodeFile(Tabs1.InputFloorPlanLocation[x]); // Log.d("inputfloorplan path",Tabs1.InputFloorPlanLocation[x].toString()); // view.bm = view.originalbitmap; // view.bitheight = view.bm.getHeight(); // view.bitwidth = view.bm.getWidth(); view.invalidate(); Canvas canvascopy = new Canvas(); Bitmap canvasbitmap = resizedbitmaponmemorycheck(); canvascopy.setBitmap(canvasbitmap); view.DONTSCALEORTRANSLATE = true; view.CanvasChanges(canvascopy); view.DONTSCALEORTRANSLATE = false; String newoutputfilestring = Tabs1.floorplanstrings.get(x).replace(Tabs1.inputfloorplandirectory, Tabs1.outputfloorplandirectory); File file = new File(newoutputfilestring); file.mkdirs(); if (file.exists()) file.delete(); FileOutputStream fos = new FileOutputStream(new File(newoutputfilestring)); Log.d("outputfloorplan path", newoutputfilestring); canvasbitmap.compress(Bitmap.CompressFormat.PNG, 100, fos); //canvasbitmap.recycle(); try { Log.d("trying outputstream flush and close", "true"); fos.flush(); fos.close(); fos = null; } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } BitmapFactory.Options o = new BitmapFactory.Options(); o.inSampleSize = Tabs1.FLOORPLANPICTURESIZE; Bitmap bm = BitmapFactory.decodeFile(newoutputfilestring, o); double calcheight = (double) Tabs1.screenheight * (double) Tabs1.FLOORPLANPICTUREDISPLAYPERCENTOFSCREEN / (double) 100; double calcwidth = (double) bm.getWidth() / (double) bm.getHeight() * (double) calcheight; int height = (int) calcheight; int width = (int) calcwidth; Bitmap resizedbitmap = null; outputfloorplanthumbnail = Bitmap.createScaledBitmap(bm, width, height, true); bm.recycle(); canvasbitmap.recycle(); } } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } //writeexcel(); //rewritewholedb(); System.out.println("database after write db"); try { Tabs1.db.showfulldblog(dbtablename); } catch (Throwable e) { } FINALBITMAPSCALE = 1; }
From source file:com.com.easemob.chatuidemo.adapter.MessageAdapter.java
public Bitmap loadBitmap(final String imageURL) { imageCache = new HashMap<String, SoftReference<Bitmap>>(); Bitmap bitmap;/*w w w . ja v a 2 s .c o m*/ option.inSampleSize = 5; if (imageCache.containsKey(imageURL)) { SoftReference<Bitmap> reference = imageCache.get(imageURL); bitmap = null; bitmap = reference.get(); if (bitmap != null) { return bitmap; } } else { String bitmapName = imageURL.substring(imageURL.lastIndexOf("/") + 1); File cacheDir = new File(Environment.getExternalStorageDirectory() + "/kaoban/"); File[] cacheFiles = cacheDir.listFiles(); int i = 0; if (null != cacheFiles) { for (; i < cacheFiles.length; i++) { if (bitmapName.equals(cacheFiles[i].getName())) { break; } } if (i < cacheFiles.length) { return BitmapFactory.decodeFile( Environment.getExternalStorageDirectory() + "/kaoban/" + bitmapName, option); } } } return null; }
From source file:com.dwdesign.tweetings.util.Utils.java
public static boolean isValidImage(final File image) { if (image == null) return false; final BitmapFactory.Options o = new BitmapFactory.Options(); o.inJustDecodeBounds = true;// www . j av a 2 s .c om BitmapFactory.decodeFile(image.getPath(), o); return o.outHeight > 0 && o.outWidth > 0; }