public Bitmap decodeThumbFile(String path) { Bitmap bmp = null; Log.v("File Path", path); File f = new File(path); try { // Decode image size BitmapFactory.Options options = new BitmapFactory.Options(); options.inTempStorage = new byte[16 * 1024]; options.inJustDecodeBounds = true; BitmapFactory.decodeStream(new FileInputStream(f), null, options); int IMAGE_MAX_SIZE = 640; int scale = 1; if (options.outHeight > IMAGE_MAX_SIZE || options.outWidth > IMAGE_MAX_SIZE) { scale = (int) Math.pow( 2, (int) Math.round( Math.log( IMAGE_MAX_SIZE / (double) Math.max(options.outHeight, options.outWidth)) / Math.log(0.5))); } // Decode with inSampleSize BitmapFactory.Options o2 = new BitmapFactory.Options(); o2.inSampleSize = scale; o2.inPurgeable = true; o2.outHeight = 480; o2.outWidth = 640; Bitmap temp = BitmapFactory.decodeStream(new FileInputStream(f), null, o2); ByteArrayOutputStream baos = new ByteArrayOutputStream(); temp.compress( Bitmap.CompressFormat.PNG, (int) (100 * ImageFileManipulation.IAMGE_COMPRESSION_RATIO), baos); temp.recycle(); temp = null; options = new BitmapFactory.Options(); options.inDither = true; options.inPurgeable = true; options.inInputShareable = true; options.inSampleSize = scale; options.inTempStorage = new byte[32 * 1024]; bmp = BitmapFactory.decodeByteArray(baos.toByteArray(), 0, baos.size(), options); } catch (Exception e) { e.printStackTrace(); } return bmp; }
private Bitmap loadResizedImage() { BitmapFactory.Options options = new BitmapFactory.Options(); options.inJustDecodeBounds = true; decode(options); int scale = 1; while (checkSize( options.outWidth / scale > mOutputWidth, options.outHeight / scale > mOutputHeight)) { scale++; } scale--; if (scale < 1) { scale = 1; } options = new BitmapFactory.Options(); options.inSampleSize = scale; options.inPreferredConfig = Bitmap.Config.RGB_565; options.inPurgeable = true; options.inTempStorage = new byte[32 * 1024]; Bitmap bitmap = decode(options); if (bitmap == null) { return null; } bitmap = rotateImage(bitmap); bitmap = scaleBitmap(bitmap); return bitmap; }
private final Bitmap compress(String uri, int reqWidth, int reqHeight) { Bitmap bitmap = null; try { BitmapFactory.Options opts = new BitmapFactory.Options(); opts.inJustDecodeBounds = true; BitmapFactory.decodeFile(uri, opts); int height = opts.outHeight; int width = opts.outWidth; int inSampleSize = 1; if (width > height && width > reqWidth) { inSampleSize = Math.round((float) width / (float) reqWidth); } else if (height > width && height > reqHeight) { inSampleSize = Math.round((float) height / (float) reqHeight); } if (inSampleSize <= 1) inSampleSize = 1; opts.inSampleSize = inSampleSize; opts.inJustDecodeBounds = false; opts.inPreferredConfig = Config.RGB_565; opts.inPurgeable = true; opts.inInputShareable = true; opts.inTargetDensity = getResources().getDisplayMetrics().densityDpi; opts.inScaled = true; opts.inTempStorage = new byte[16 * 1024]; bitmap = BitmapFactory.decodeStream(new BufferedInputStream(new FileInputStream(uri)), null, opts); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (OutOfMemoryError e) { e.printStackTrace(); } return bitmap; }
private CloseableReference<Bitmap> decodeStaticImageFromStream( InputStream inputStream, BitmapFactory.Options options) { Preconditions.checkNotNull(inputStream); int sizeInBytes = BitmapUtil.getSizeInByteForBitmap( options.outWidth, options.outHeight, options.inPreferredConfig); final Bitmap bitmapToReuse = mBitmapPool.get(sizeInBytes); if (bitmapToReuse == null) { throw new NullPointerException("BitmapPool.get returned null"); } options.inBitmap = bitmapToReuse; Bitmap decodedBitmap; ByteBuffer byteBuffer = mDecodeBuffers.acquire(); if (byteBuffer == null) { byteBuffer = ByteBuffer.allocate(DECODE_BUFFER_SIZE); } try { options.inTempStorage = byteBuffer.array(); decodedBitmap = BitmapFactory.decodeStream(inputStream, null, options); } catch (RuntimeException re) { mBitmapPool.release(bitmapToReuse); throw re; } finally { mDecodeBuffers.release(byteBuffer); } if (bitmapToReuse != decodedBitmap) { mBitmapPool.release(bitmapToReuse); decodedBitmap.recycle(); throw new IllegalStateException(); } return CloseableReference.of(decodedBitmap, mBitmapPool); }
private void saveImage(byte[] data) { try { BitmapFactory.Options opts = new BitmapFactory.Options(); opts.inJustDecodeBounds = true; BitmapFactory.decodeByteArray(data, 0, data.length, opts); DisplayMetrics dm = new DisplayMetrics(); getWindowManager().getDefaultDisplay().getMetrics(dm); opts.inSampleSize = calculateInSampleSize(opts, dm.heightPixels, dm.widthPixels); opts.inPurgeable = true; opts.inInputShareable = true; opts.inTempStorage = new byte[64 * 1024]; opts.inJustDecodeBounds = false; Bitmap bm = BitmapFactory.decodeByteArray(data, 0, data.length, opts); if (bm != null) { bm = Util.rotate(bm, getRotate()); File file = new File(filePath); BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(file)); bm.compress(Bitmap.CompressFormat.JPEG, 100, bos); bos.flush(); bos.close(); } } catch (Exception e) { e.printStackTrace(); } }
private static BitmapFactory.Options getOptions() { // Android specific options final BitmapFactory.Options options = new BitmapFactory.Options(); options.inDither = true; options.inPurgeable = true; options.inTempStorage = mTempStorage; // Probably not used as ARGB_8888 has already been set options.inPreferredConfig = Config.RGB_565; return options; }
/** * Return bitmap through by resources. * * @param res * @param is * @param width * @param height * @return bitmap */ public static Bitmap getBitmap(InputStream is, int width, int height) { BitmapFactory.Options options = new BitmapFactory.Options(); options.inTempStorage = new byte[TEMP_STORAGE_SIZE]; options.inPreferredConfig = Bitmap.Config.RGB_565; options.inPurgeable = true; options.inInputShareable = true; options.inSampleSize = calculateInSampleSize(options, width, height); options.inJustDecodeBounds = false; return BitmapFactory.decodeStream(is, null, options); }
public Jpeg(Activity a, String in_file_name, int quality, String out_file_name) { if (!root_dir.exists()) root_dir.mkdir(); this.a = a; String string = new String(); inFile = new File(in_file_name); if (in_file_name.endsWith(".jpg") && !in_file_name.endsWith(".tif") && !in_file_name.endsWith(".gif")) { StandardUsage(); } if (out_file_name == null) { string = inFile.getName().substring(0, inFile.getName().lastIndexOf(".")) + ".jpg"; } else { string = out_file_name; if (string.endsWith(".tif") || string.endsWith(".gif")) { string = string.substring(0, string.lastIndexOf(".")); } if (!string.endsWith(".jpg")) { string = string.concat(".jpg"); } } outFile = new File(root_dir, string); if (inFile.exists()) { try { dataOut = new FileOutputStream(outFile); } catch (final IOException e) { Log.e(LOG, e.toString()); e.printStackTrace(); } Quality = quality; opts = new BitmapFactory.Options(); opts.inDither = false; opts.inPurgeable = true; opts.inInputShareable = true; opts.inTempStorage = new byte[32 * 1024]; // image = BitmapFactory.decodeFile(in_file_name, opts); image = BitmapFactory.decodeFile(in_file_name); jpg = new JpegEncoder(image, Quality, dataOut, ""); } else { // TODO: could not find the in file-- throw error Log.e(LOG, "could not find the inFile? (" + inFile.getAbsolutePath() + ")"); return; } }
/** * 通过简单处理后获取res中的bitmap对象 * * @param paramResources * @param res * @param width 长度 * @param height 高度 * @return bitmap 对象 */ public static Bitmap decodeSampledBitmapFromResource( Resources paramResources, int res, int width, int height) { InputStream localInputStream = paramResources.openRawResource(res); BitmapFactory.Options localOptions = new BitmapFactory.Options(); localOptions.inTempStorage = new byte[TEMP_STORAGE_SIZE]; localOptions.inPreferredConfig = Bitmap.Config.RGB_565; localOptions.inPurgeable = true; localOptions.inInputShareable = true; localOptions.inSampleSize = calculateInSampleSize(localOptions, width, height); localOptions.inJustDecodeBounds = false; return BitmapFactory.decodeStream(localInputStream, null, localOptions); }
/** * Return bitmap through by imagePath. * * @param imagePath * @param width * @param height * @return bitmap */ public static Bitmap getBitmap(String imagePath, int width, int height) { if (imagePath == null || "".equals(imagePath)) { return null; } BitmapFactory.Options options = new BitmapFactory.Options(); options.inTempStorage = new byte[TEMP_STORAGE_SIZE]; options.inPreferredConfig = Bitmap.Config.RGB_565; options.inPurgeable = true; options.inInputShareable = true; options.inSampleSize = calculateInSampleSize(options, width, height); options.inJustDecodeBounds = false; return BitmapFactory.decodeFile(imagePath, options); }
@Override protected Boolean doInBackground(Void... params) { // QRCodeClient client = new QRCodeClient(); // For scanning a file from /res folder // InputStream fileInputStream = // getResources().openRawResource(R.drawable.qr_code_test_p); BitmapFactory.Options bfOptions = new BitmapFactory.Options(); bfOptions.inDither = false; // Disable Dithering mode bfOptions.inPurgeable = true; // Tell to gc that whether it needs // free memory, the Bitmap can be // cleared bfOptions.inInputShareable = true; // Which kind of reference will // be used to recover the Bitmap // data after being clear, when // it will be used in the future bfOptions.inTempStorage = new byte[32 * 1024]; Bitmap bMap = BitmapFactory.decodeFile(path, bfOptions); bMap = Bitmap.createScaledBitmap(bMap, 1200, 900, false); // Lets // change // size // to a // bit // smaller, // I // didn't // experiment // a lot // with // it so // it // can // be // not // optimal ByteArrayOutputStream bos = new ByteArrayOutputStream(); bMap.compress(CompressFormat.PNG, 0, bos); byte[] bitmapdata = bos.toByteArray(); ByteArrayInputStream fileInputStream = new ByteArrayInputStream(bitmapdata); BufferedInputStream bis = new BufferedInputStream(fileInputStream); try { // content = client.decode(bis); } catch (Exception e) { e.printStackTrace(); } SimpleDateFormat sdf = new SimpleDateFormat("HH:mm dd.MM", java.util.Locale.getDefault()); Date dt = new Date(); date = sdf.format(dt); return true; }
public Bitmap createBitmapFromUri(Uri uri) { Bitmap imageBitmap = null; try { ContentResolver contentResolver = context.getContentResolver(); InputStream inputStream = contentResolver.openInputStream(uri); BitmapFactory.Options opt = new BitmapFactory.Options(); opt.inTempStorage = new byte[16 * 1024]; opt.inSampleSize = 1; opt.outWidth = 50; opt.outHeight = 40; imageBitmap = BitmapFactory.decodeStream(inputStream, new Rect(), null); } catch (FileNotFoundException e) { e.printStackTrace(); } return imageBitmap; }
public cgHtmlImg( Activity activityIn, cgSettings settingsIn, String geocodeIn, boolean placementIn, int reasonIn, boolean onlySaveIn) { activity = activityIn; settings = settingsIn; geocode = geocodeIn; placement = placementIn; reason = reasonIn; onlySave = onlySaveIn; bfOptions.inTempStorage = new byte[16 * 1024]; }
/** * 根据图像URL创建Bitmap * * @param url URL地址 * @return bitmap */ public Bitmap CreateImage(String url) { // Logger.d("ImageDownloader", // "开始调用CreateImage():" + System.currentTimeMillis()); Bitmap bitmap = null; if (url == null || url.equals("")) { return null; } try { // Logger.d( // "ImageDownloader", // "C Before SDCard decodeStream==>" + "Heap:" // + (Debug.getNativeHeapSize() / 1024) + "KB " // + "FreeHeap:" // + (Debug.getNativeHeapFreeSize() / 1024) + "KB " // + "AllocatedHeap:" // + (Debug.getNativeHeapAllocatedSize() / 1024) // + "KB" + " url:" + url); FileInputStream fis = new FileInputStream(url); BitmapFactory.Options opts = new BitmapFactory.Options(); opts.inPreferredConfig = Bitmap.Config.ARGB_4444; opts.inTempStorage = new byte[100 * 1024]; opts.inPurgeable = true; opts.inInputShareable = true; bitmap = BitmapFactory.decodeStream(fis, null, opts); // Logger.d( // "ImageDownloader", // "C After SDCard decodeStream==>" + "Heap:" // + (Debug.getNativeHeapSize() / 1024) + "KB " // + "FreeHeap:" // + (Debug.getNativeHeapFreeSize() / 1024) + "KB " // + "AllocatedHeap:" // + (Debug.getNativeHeapAllocatedSize() / 1024) // + "KB" + " url:" + url); } catch (OutOfMemoryError e) { LogUtils.e("OutOfMemoryError", e); System.gc(); } catch (FileNotFoundException e) { LogUtils.e("FileNotFoundException", e); } // Logger.d("ImageDownloader", // "结束调用CreateImage():" + System.currentTimeMillis()); return bitmap; }
@Override protected void onProgressUpdate(String... values) { File file = new File(values[0]); if (file.getName().toLowerCase().endsWith(".jpg") || file.getName().toLowerCase().endsWith(".png") || file.getName().toLowerCase().endsWith(".gif") || file.getName().toLowerCase().endsWith(".jpeg")) { if (myBitmap != null) { myBitmap = null; } BitmapFactory.Options opts = new BitmapFactory.Options(); opts.inDither = false; opts.inTempStorage = new byte[1024 * 1024]; myBitmap = BitmapFactory.decodeFile(file.getAbsolutePath(), opts); video.setVisibility(View.INVISIBLE); imagem.setVisibility(View.VISIBLE); // imagem.setImageBitmap(myBitmap); imagem.post( new Runnable() { @Override public void run() { imagem.setImageBitmap(myBitmap); } }); } else if (file.getName().toLowerCase().endsWith(".avi") || file.getName().toLowerCase().endsWith(".mp4") || file.getName().toLowerCase().endsWith(".mpeg")) { video.setVisibility(View.VISIBLE); imagem.setVisibility(View.INVISIBLE); video.setVideoPath(file.getAbsolutePath()); video.setOnPreparedListener( new MediaPlayer.OnPreparedListener() { @Override public void onPrepared(MediaPlayer mp) { video.start(); duracao = video.getDuration(); } }); } }
/** @return Bitmap or null... */ private static Bitmap getCustomResourceSampled( final Context context, final int resourceID, final int reqWidth, final int reqHeight) { final BitmapFactory.Options options = new BitmapFactory.Options(); options.inPreferredConfig = Bitmap.Config.ARGB_8888; options.inDither = false; // Disable Dithering mode options.inPurgeable = true; // Tell to gc that whether it needs free // memory, the Bitmap can be cleared options.inInputShareable = true; // Which kind of reference will be // used to recover the Bitmap // data after being clear, when // it will be used in the future options.inTempStorage = new byte[32 * 1024]; options.inJustDecodeBounds = true; BitmapFactory.decodeResource(context.getResources(), resourceID, options); // Calculate inSampleSize options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight); // Decode bitmap with inSampleSize set options.inJustDecodeBounds = false; final Bitmap b = BitmapFactory.decodeResource(context.getResources(), resourceID, options); return b; }
/** * 从本地SD卡中获取图片 * * @param imgPath 图片路径 * @return 图片的Bitmap */ private Bitmap getSDBitmap(String imgPath) { Bitmap bm = null; BitmapFactory.Options options = new BitmapFactory.Options(); /** 设置临时缓存大小 */ options.inTempStorage = new byte[1024 * 1024]; /** * 通过设置Options.inPreferredConfig值来降低内存消耗: 默认为ARGB_8888: 每个像素4字节. 共32位。 Alpha_8: 只保存透明度,共8位,1字节。 * ARGB_4444: 共16位,2字节。 RGB_565:共16位,2字节 */ options.inPreferredConfig = Bitmap.Config.RGB_565; /** * inPurgeable:设置为True,则使用BitmapFactory创建的Bitmap用于存储Pixel的内存空间, * 在系统内存不足时可以被回收,当应用需要再次访问该Bitmap的Pixel时,系统会再次调用BitmapFactory 的decode方法重新生成Bitmap的Pixel数组。 * 设置为False时,表示不能被回收。 */ options.inPurgeable = true; options.inInputShareable = true; /** 设置decode时的缩放比例。 */ options.inSampleSize = 1; bm = BitmapFactory.decodeFile(imgPath, options); return bm; }
/** * Load a previously saved image. * * @param file the file on disk * @param forceKeep keep the image if it is there, without checking its freshness * @return a pair with <code>true</code> in the second component if the image was there and is * fresh enough or <code>false</code> otherwise, and the image (possibly <code>null</code> if * the second component is <code>false</code> and the image could not be loaded, or if the * second component is <code>true</code> and <code>onlySave</code> is also <code>true</code>) */ @NonNull private ImmutablePair<Bitmap, Boolean> loadCachedImage(final File file, final boolean forceKeep) { if (file.exists()) { final boolean freshEnough = listId >= StoredList.STANDARD_LIST_ID || file.lastModified() > (System.currentTimeMillis() - (24 * 60 * 60 * 1000)) || forceKeep; if (freshEnough && onlySave) { return ImmutablePair.of((Bitmap) null, true); } final BitmapFactory.Options bfOptions = new BitmapFactory.Options(); bfOptions.inTempStorage = new byte[16 * 1024]; bfOptions.inPreferredConfig = Bitmap.Config.RGB_565; setSampleSize(file, bfOptions); final Bitmap image = BitmapFactory.decodeFile(file.getPath(), bfOptions); if (image == null) { Log.e("Cannot decode bitmap from " + file.getPath()); return ImmutablePair.of((Bitmap) null, false); } return ImmutablePair.of(image, freshEnough); } return ImmutablePair.of((Bitmap) null, false); }
/** * Out of Memory hack taken from here http://stackoverflow.com/a/7116158/527759 * * @param path * @return */ Bitmap getBitmap(String path) { Bitmap bm = null; BitmapFactory.Options bfOptions = new BitmapFactory.Options(); bfOptions.inDither = false; // Disable Dithering mode bfOptions.inPurgeable = true; // Tell to gc that whether it needs // free memory, the Bitmap can be // cleared bfOptions.inInputShareable = true; // Which kind of reference will // be used to recover the Bitmap // data after being clear, when // it will be used in the future bfOptions.inTempStorage = new byte[32 * 1024]; File file = new File(path); FileInputStream fs = null; try { fs = new FileInputStream(file); } catch (FileNotFoundException e) { // TODO do something intelligent e.printStackTrace(); } try { if (fs != null) bm = BitmapFactory.decodeFileDescriptor(fs.getFD(), null, bfOptions); } catch (IOException e) { // GuiUtils.error(TAG, null, e); } finally { if (fs != null) { try { fs.close(); } catch (IOException e) { e.printStackTrace(); } } } return bm; }
/** @return Bitmap or null... */ public static Bitmap getCustomImageSampled( final String filePath, final int reqWidth, final int reqHeight) { if (!filePath.equals("aaa")) { final BitmapFactory.Options options = new BitmapFactory.Options(); options.inPreferredConfig = Bitmap.Config.ARGB_8888; options.inDither = false; // Disable Dithering mode options.inPurgeable = true; // Tell to gc that whether it needs free // memory, the Bitmap can be cleared options.inInputShareable = true; // Which kind of reference will be // used to recover the Bitmap // data after being clear, when // it will be used in the future options.inTempStorage = new byte[32 * 1024]; options.inJustDecodeBounds = true; BitmapFactory.decodeFile(filePath, options); // Calculate inSampleSize options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight); // Decode bitmap with inSampleSize set options.inJustDecodeBounds = false; final Bitmap b = BitmapFactory.decodeFile(filePath, options); return b; } return null; }
public LoadNaturalSiblingTask(int slot) { mOptions = new BitmapFactory.Options(); mOptions.inTempStorage = new byte[32768]; mSlot = slot; }
static { sBFOptions.inDither = false; sBFOptions.inPurgeable = true; // allow this memory to be reclaimed sBFOptions.inInputShareable = true; // share the reference, rather than copy sBFOptions.inTempStorage = new byte[32 * 1024]; // allocate temporary memory }
@Override public void Initialize() { String tagName = new String(); int frameWidth = 0; int frameHeight = 0; int numFrame = 0; int XCenterPoint = 0; int YCenterPoint = 0; int bitmapResID = 0; XmlResourceParser xrp = Game().getResources().getXml(_xmlResID); try { while (xrp.getEventType() != XmlResourceParser.END_DOCUMENT) { if (xrp.getEventType() == XmlResourceParser.START_TAG) { tagName = xrp.getName(); if (tagName.equals("Definition")) { numFrame = xrp.getAttributeIntValue(null, "NumFrame", 0); frameWidth = xrp.getAttributeIntValue(null, "FrameWidth", 0); frameHeight = xrp.getAttributeIntValue(null, "FrameHeight", 0); XCenterPoint = xrp.getAttributeIntValue(null, "XCenterPoint", 0); YCenterPoint = xrp.getAttributeIntValue(null, "YCenterPoint", 0); bitmapResID = xrp.getAttributeResourceValue(null, "SheetName", 0); } } else if (xrp.getEventType() == XmlResourceParser.END_TAG) { // Chinh tham so Bitmap Factory de tranh loi Out of Memory khi kich thuoc bitmap qua lon BitmapFactory.Options bfOption = new BitmapFactory.Options(); bfOption.inDither = false; // Disable Dithering mode bfOption.inPurgeable = true; // Tell to gc (Garbage Collection) that whether it needs free memory, the Bitmap // can be cleared bfOption.inInputShareable = true; // Which kind of reference will be used to recover the Bitmap data after being // clear, when it will be used in the future bfOption.inTempStorage = new byte[32 * 1024]; Sprite sprite = new Sprite( null, BitmapFactory.decodeResource(Game().getResources(), bitmapResID, bfOption), numFrame, new Vector2(frameWidth, frameHeight), new Vector2(XCenterPoint, YCenterPoint), true); _sprites.add(sprite); } else if (xrp.getEventType() == XmlResourceParser.TEXT) { } xrp.next(); } xrp.close(); } catch (XmlPullParserException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } super.Initialize(); }
public PhotoLaunchTask() { mOptions = new BitmapFactory.Options(); mOptions.inTempStorage = new byte[32768]; }
/** * 图片缩放处理,并保存到SDCard * * @param byteArrayOutputStream 图片字节流 * @param screen 屏幕宽高 * @param url 图片网络路径 * @param cachePath 本地缓存父路径</br>PathCommonDefines.PHOTOCACHE_FOLDER 程序缓存图片路径;</br> * PathCommonDefines.MY_FAVOURITE_FOLDER 我的收藏图片路径 * @param isJpg 是否是Jpg * @return 缩放后的图片bitmap */ public static Bitmap saveZoomBitmapToSDCard( ByteArrayOutputStream byteArrayOutputStream, Screen screen, String url, String cachePath, boolean isJpg) { Bitmap bitmap = null; try { byte[] byteArray = byteArrayOutputStream.toByteArray(); BitmapFactory.Options options = new BitmapFactory.Options(); options.inTempStorage = new byte[16 * 1024]; // 只加载图片的边界 options.inJustDecodeBounds = true; // 获取Bitmap信息 BitmapFactory.decodeByteArray(byteArray, 0, byteArray.length, options); // 获取屏幕的宽和高 int screenWidth = screen.widthPixels; int screenHeight = screen.heightPixels; // 屏幕最大像素个数 int maxNumOfPixels = screenWidth * screenHeight; // 计算采样率 int sampleSize = computeSampleSize(options, -1, maxNumOfPixels); options.inSampleSize = sampleSize; options.inJustDecodeBounds = false; // 重新读入图片,此时为缩放后的图片 bitmap = BitmapFactory.decodeByteArray(byteArray, 0, byteArray.length, options); // 压缩比例 int quality = 100; // 判断是否是Jpg,png是无损压缩,所以不用进行质量压缩 if (bitmap != null && isJpg) { ByteArrayOutputStream saveBaos = new ByteArrayOutputStream(); bitmap.compress(Bitmap.CompressFormat.JPEG, quality, saveBaos); // 循环判断如果压缩后图片是否大于100kb,大于继续压缩 while (saveBaos.toByteArray().length / 1024 > 100) { // 重置saveBaos即清空saveBaos saveBaos.reset(); // 每次都减少10 quality -= 10; // 这里压缩optionsNum%,把压缩后的数据存放到saveBaos中 bitmap.compress(Bitmap.CompressFormat.JPEG, quality, saveBaos); } // 把压缩后的数据ByteArrayOutputStream存放到ByteArrayInputStream中 ByteArrayInputStream saveBais = new ByteArrayInputStream(saveBaos.toByteArray()); bitmap = BitmapFactory.decodeStream(saveBais, null, null); } // 保存到SDCard ImageSDCacher.getImageSDCacher().saveBitmapToSDCard(bitmap, url, cachePath, isJpg, quality); } catch (Exception e) { Log.e("saveZoomBitmapToSDCard", "" + e); } return bitmap; }
private BitmapFactory.Options createBitmapOptions() { BitmapFactory.Options options = new BitmapFactory.Options(); options.inTempStorage = manager.getBuffersPool().get(IMAGES_BUFFER_SIZE); options.inPreferredConfig = format; return options; }
@Override public void run() { try { final int BUF_SIZE = 100 * 1024; buf = new byte[BUF_SIZE]; String scheme = u.getScheme(); if (ContentResolver.SCHEME_CONTENT.equals(scheme)) { BitmapFactory.Options options = new BitmapFactory.Options(); options.inTempStorage = buf; InputStream is = null; for (int b = 1; b < 0x80000; b <<= 1) { try { options.inSampleSize = b; is = getContentResolver().openInputStream(u); if (is == null) { Log.e(TAG, "Failed to get the content stream for: " + u); return; } bmp = BitmapFactory.decodeStream(is, null, options); if (bmp != null) return; } catch (Throwable e) { } finally { if (is != null) is.close(); } Log.w(TAG, "Cant decode stream to bitmap. b=" + b); } } else { File f = null; setPriority(Thread.MAX_PRIORITY); boolean local = CA.isLocal(scheme); if (local) { // pre-cache in a file f = new File(u.getPath()); } else { CommanderAdapter ca = null; FileOutputStream fos = null; InputStream is = null; try { ca = CA.CreateAdapterInstance(CA.GetAdapterTypeId(scheme), ctx); if (ca == null) return; Credentials crd = null; try { crd = (Credentials) getIntent().getParcelableExtra(Credentials.KEY); } catch (Exception e) { Log.e(TAG, "on taking credentials from parcel", e); } ca.setCredentials(crd); // output - temporary file File pictvw_f = ctx.getDir("pictvw", Context.MODE_PRIVATE); if (pictvw_f == null) return; f = new File(pictvw_f, "file.tmp"); fos = new FileOutputStream(f); // input - the content from adapter is = ca.getContent(u); if (is == null) return; int n; boolean available_supported = is.available() > 0; while ((n = is.read(buf)) != -1) { // Log.v( "readStreamToBuffer", "Read " + n + " bytes" ); // sendProgress( tot += n ); Thread.sleep(1); fos.write(buf, 0, n); if (available_supported) { for (int i = 0; i < 10; i++) { if (is.available() > 0) break; // Log.v( "readStreamToBuffer", "Waiting the rest " + i ); Thread.sleep(20); } if (is.available() == 0) { // Log.v( "readStreamToBuffer", "No more data!" ); break; } } } } catch (Throwable e) { throw e; } finally { if (ca != null) { if (is != null) ca.closeStream(is); ca.prepareToDestroy(); } if (fos != null) fos.close(); } } if (f != null) { BitmapFactory.Options options = new BitmapFactory.Options(); options.inTempStorage = buf; for (int b = 1; b < 0x80000; b <<= 1) { try { options.inSampleSize = b; bmp = BitmapFactory.decodeFile(f.getAbsolutePath(), options); } catch (Throwable e) { } if (bmp != null) { if (!local) f.delete(); return; } } } } } catch (Throwable e) { Log.e(TAG, u != null ? u.toString() : null, e); msgText = e.getLocalizedMessage(); } finally { sendProgress(-1); } }
private void init(View view) { objPrescriptionModel = new PrescriptionModel(); buttonAddPrescription = (ButtonFloat) view.findViewById(R.id.buttonFloat); buttonUploadPrescription = (Button) view.findViewById(R.id.buttonUPloadPrescription); // prescriptionDoc = (ImageView)view.findViewById(R.id.imageViewUploadPrescription); linearLayoutAddPres = (LinearLayout) view.findViewById(R.id.linearLayoutAdd); // listViewPres = (ListView)view.findViewById(R.id.listViewData); editTextDoctorAdd = (AutoCompleteTextView) view.findViewById(R.id.editTextDoctorAdd); buttonSend = (Button) view.findViewById(R.id.buttonSendPrescription); linearLayoutEmpty = (LinearLayout) view.findViewById(R.id.emptyView); layoutAddPhotos = (LinearLayout) view.findViewById(R.id.linearLayoutUploadPhotos); radioGroupOffer = (RadioGroup) view.findViewById(R.id.radioGroupOffer); radioButtonFifteen = (RadioButton) view.findViewById(R.id.homdeDeleiveryThree); radioButtonThirty = (RadioButton) view.findViewById(R.id.homdeDeleiveryeight); textViewNote = (TextView) view.findViewById(R.id.textViewNote); buttonNext = (Button) view.findViewById(R.id.buttonNext); textViewUploadedPrescrition = (TextView) view.findViewById(R.id.textViewUploadedPrescription); // Let's get the root layout and add our ImageView layout = (LinearLayout) view.findViewById(R.id.root); objHorizontalScrollView = (HorizontalScrollView) view.findViewById(R.id.horizontalScrollView1); // imageViewClose = (ImageView)view.findViewById(R.id.imageViewClose); listOfImagesPath = null; listOfImagesPath = RetriveCapturedImagePath(); if (listOfImagesPath != null && listOfImagesPath.size() != 0) { /* Log.d("list", "size in creaetView"+listOfImagesPath.size()); //gridImages.setAdapter(new CustomGridImage(getActivity(),listOfImagesPath)); for(int i=0;i<listOfImagesPath.size();i++){ ImageView image = new ImageView(getActivity()); // Now the layout parameters, these are a little tricky at first FrameLayout.LayoutParams params = new FrameLayout.LayoutParams( 300, 400); FrameLayout framelayout = new FrameLayout(getActivity()); framelayout.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT)); ImageView imageView = new ImageView(getActivity()); imageView.setScaleType(ImageView.ScaleType.CENTER_CROP); imageView.setImageResource(R.drawable.ic_account_search_grey600_36dp); imageView.setRight(1); image.setScaleType (ImageView.ScaleType.FIT_XY); image.setPadding(10, 0, 10, 0); try { fs = new FileInputStream(new File(listOfImagesPath.get(i).toString())); if(fs!=null) { bm=BitmapFactory.decodeFileDescriptor(fs.getFD(), null, bfOptions); image.setImageBitmap(bm); image.setId(i); } } catch (IOException e) { e.printStackTrace(); } finally{ if(fs!=null) { try { fs.close(); } catch (IOException e) { e.printStackTrace(); } } } framelayout.addView(image); framelayout.addView(imageView); layout.addView(framelayout, 0, params); buttonUploadPrescription.setText("Add another prescription"); } */ } else { textViewUploadedPrescrition.setText("No Prescription Uploded Yet!!!"); buttonSend.setEnabled(false); } buttonAddPrescription.setOnClickListener(this); buttonSend.setOnClickListener(this); buttonUploadPrescription.setOnClickListener(this); buttonNext.setOnClickListener(this); radioGroupOffer.setOnCheckedChangeListener(this); textViewNote.setText( Html.fromHtml("Ensure the prescription image captures the doctors details clearly")); textViewNote.setMovementMethod(LinkMovementMethod.getInstance()); SessionManager session = new SessionManager(getActivity()); User user = session.getUserDetails(); String address = user.getAddress(); editTextDoctorAdd.setText(address); bfOptions = new BitmapFactory.Options(); bfOptions.inDither = false; // Disable Dithering mode bfOptions.inPurgeable = true; // Tell to gc that whether it needs free memory, the Bitmap can be cleared bfOptions.inInputShareable = true; // Which kind of reference will be used to recover the Bitmap data after being clear, // when it will be used in the future bfOptions.inTempStorage = new byte[32 * 1024]; }