/** * 获取图片文件的宽高,宽高封装在Point的X和Y中 * * @param filePath 文件路径 */ public static Point getPicWH(String filePath) { Point point = new Point(); try { BitmapFactory.Options options = new BitmapFactory.Options(); options.inJustDecodeBounds = true; Bitmap bmp = BitmapFactory.decodeFile(filePath, options); point.x = options.outWidth; point.y = options.outHeight; options.inJustDecodeBounds = false; } catch (Exception e) { e.printStackTrace(); } return point; }
@Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { switch (requestCode) { case GET_PHOTO: if (resultCode == RESULT_OK) { crop(data.getData()); } break; case TAKE_PHOTO: if (resultCode == RESULT_OK) { crop(headImgUri); } break; case CROP_PHOTO: if (resultCode == RESULT_OK) { Bitmap cropBitmap = data.getParcelableExtra("data"); String path = mUriFile.getPath(); watermarkUrl = path; pickDirectory.setImageBitmap(cropBitmap); mCustomPopupWindow.dismiss(); } break; default: break; } }
/** * @param b Bitmap * @return 图片存储的位置 */ public static File saveImg(Bitmap b, String name) throws Exception { String path = Environment.getExternalStorageDirectory().getPath() + File.separator + "test/headImg/"; File mediaFile = new File(path + File.separator + name + ".jpg"); if (mediaFile.exists()) { mediaFile.delete(); } if (!new File(path).exists()) { new File(path).mkdirs(); } mediaFile.createNewFile(); FileOutputStream fos = new FileOutputStream(mediaFile); b.compress(Bitmap.CompressFormat.PNG, 100, fos); fos.flush(); fos.close(); b.recycle(); b = null; System.gc(); // return mediaFile.getPath(); return mediaFile; }
public Bitmap getBitmapByView(View v) { Bitmap bitmap = Bitmap.createBitmap(v.getWidth(), v.getHeight(), Bitmap.Config.ARGB_8888); Canvas canvas = new Canvas(bitmap); v.draw(canvas); return bitmap; }
@Test public void testDetFace() { Bitmap bitmap = BitmapFactory.decodeFile("/sdcard/test.jpg"); assertThat(bitmap, notNullValue()); FaceDet faceDet = new FaceDet(Constants.getFaceShapeModelPath()); List<VisionDetRet> results = faceDet.detect("/sdcard/test.jpg"); for (final VisionDetRet ret : results) { String label = ret.getLabel(); int rectLeft = ret.getLeft(); int rectTop = ret.getTop(); int rectRight = ret.getRight(); int rectBottom = ret.getBottom(); assertThat(label, is("face")); Assert.assertTrue(rectLeft > 0); } faceDet.release(); }
/** * 获取圆形图片方法 * @param bitmap * @param pixels * @return Bitmap * @author caizhiming */ private Bitmap getCircleBitmap(Bitmap bitmap, int pixels) { Bitmap output = Bitmap.createBitmap(bitmap.getWidth(), bitmap.getHeight(), Bitmap.Config.ARGB_8888); Canvas canvas = new Canvas(output); final int color = 0xff424242; final Rect rect = new Rect(0, 0, bitmap.getWidth(), bitmap.getHeight()); paint.setAntiAlias(true); canvas.drawARGB(0, 0, 0, 0); paint.setColor(color); int x = bitmap.getWidth(); canvas.drawCircle(x / 2, x / 2, x / 2, paint); paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN)); canvas.drawBitmap(bitmap, rect, rect, paint); return output; }
protected Bitmap decodeFileDescriptorAsPurgeable( CloseableReference<PooledByteBuffer> bytesRef, int inputLength, byte[] suffix, BitmapFactory.Options options) { MemoryFile memoryFile = null; try { memoryFile = copyToMemoryFile(bytesRef, inputLength, suffix); FileDescriptor fd = getMemoryFileDescriptor(memoryFile); Bitmap bitmap = sWebpBitmapFactory.decodeFileDescriptor(fd, null, options); return Preconditions.checkNotNull(bitmap, "BitmapFactory returned null"); } catch (IOException e) { throw Throwables.propagate(e); } finally { if (memoryFile != null) { memoryFile.close(); } } }
/** * 对Activity截图 * * @param activity * @return Bitmap对象。 */ public static Bitmap takeScreenShot(Activity activity) { View view = activity.getWindow().getDecorView(); view.setDrawingCacheEnabled(true); view.buildDrawingCache(); Bitmap b1 = view.getDrawingCache(); Rect frame = new Rect(); activity.getWindow().getDecorView().getWindowVisibleDisplayFrame(frame); int statusBarHeight = frame.top; int width = activity.getWindowManager().getDefaultDisplay().getWidth(); int height = activity.getWindowManager().getDefaultDisplay() .getHeight(); Bitmap b = Bitmap.createBitmap(b1, 0, statusBarHeight, width, height - statusBarHeight); view.destroyDrawingCache(); return b; }
/** * Compress bitmap using jpeg, convert to Base64 encoded string, and return to JavaScript. * * @param bitmap */ public void processPicture(Bitmap bitmap) { ByteArrayOutputStream jpeg_data = new ByteArrayOutputStream(); try { if (bitmap.compress(CompressFormat.JPEG, mQuality, jpeg_data)) { byte[] code = jpeg_data.toByteArray(); byte[] output = Base64.encode(code, Base64.NO_WRAP); String js_out = new String(output); this.callbackContext.success(js_out); js_out = null; output = null; code = null; } } catch (Exception e) { this.failPicture("Error compressing image."); } jpeg_data = null; }
public static void blur(Bitmap bkg, View view) { long startMs = System.currentTimeMillis(); float radius = 15; float scaleFactor = 8; //放大到整个view的大小 bkg = DrawableProvider.getReSizeBitmap(bkg, view.getMeasuredWidth(), view.getMeasuredHeight()); Bitmap overlay = Bitmap.createBitmap((int) (view.getMeasuredWidth() / scaleFactor) , (int) (view.getMeasuredHeight() / scaleFactor), Bitmap.Config.ARGB_8888); Canvas canvas = new Canvas(overlay); canvas.translate(-view.getLeft() / scaleFactor, -view.getTop() / scaleFactor); canvas.scale(1 / scaleFactor, 1 / scaleFactor); Paint paint = new Paint(); paint.setFlags(Paint.FILTER_BITMAP_FLAG); canvas.drawBitmap(bkg, 0, 0, paint); overlay = FastBlur.doBlur(overlay, (int) radius, true); view.setBackgroundDrawable(new BitmapDrawable(UiUtils.getResources(), overlay)); Log.w("test", "cost " + (System.currentTimeMillis() - startMs) + "ms"); }
/** * 上传用户信息,首先上传头像,上传成功后赶回头像地址,然后上传其他信息 */ private void updateUserInfo(Bitmap avatar) { //如果头像为空,也就是用户没有上传头像,则使用之前的头像地址 if (avatar == null) { } else { final AVFile avatarFile = new AVFile("user_avatar.jpeg", ImageUtil.bitmap2Bytes(avatar)); avatarFile.saveInBackground(new SaveCallback() { @Override public void done(AVException e) { if (e == null) { Log.i("lin", "----lin----> imgUrl" + avatarFile.getUrl()); _cardView = avatarFile.getUrl(); } } }); } }
public void update(Following following, boolean fling) { tvName.setText(following.screenName); ivCheck.setImageBitmap(following.checked ? bmChd : bmUnch); if (aivIcon != null) { if (fling) { Bitmap bm = BitmapProcessor.getBitmapFromCache(following.icon); if (bm != null && !bm.isRecycled()) { aivIcon.setImageBitmap(bm); } else { aivIcon.execute(null, 0); } } else { aivIcon.execute(following.icon, 0); } } }
public static Bitmap decodeSampled(InputStream is, int reqWidth, int reqHeight) { BitmapFactory.Options options = new BitmapFactory.Options(); // RGB_565 options.inPreferredConfig = Bitmap.Config.RGB_565; // sample size options.inSampleSize = getSampleSize(is, reqWidth, reqHeight); try { return BitmapFactory.decodeStream(is, null, options); } catch (OutOfMemoryError e) { e.printStackTrace(); } return null; }
@Override public void onClientMetadataUpdate(RemoteController.MetadataEditor metadataEditor) { meta=metadataEditor; StandardWidget.currentArt=metadataEditor.getBitmap(MediaMetadataEditor.BITMAP_KEY_ARTWORK,null); StandardWidget.currentSquareArt = StandardWidget.currentArt; if(StandardWidget.currentArt!=null) { int cah = StandardWidget.currentArt.getHeight(); int caw = StandardWidget.currentArt.getWidth(); if (caw > cah * 1.02) { StandardWidget.currentSquareArt = Bitmap.createBitmap(StandardWidget.currentArt, (int) (caw / 2 - cah * 0.51), 0, (int) (cah * 1.02), cah); } } StandardWidget.currentArtist=metadataEditor.getString(MediaMetadataRetriever.METADATA_KEY_ARTIST,""); StandardWidget.currentSong=metadataEditor.getString(MediaMetadataRetriever.METADATA_KEY_TITLE,""); StandardWidget.currentAlbum=metadataEditor.getString(MediaMetadataRetriever.METADATA_KEY_ALBUM,""); if(StandardWidget.currentArtist==null||StandardWidget.currentArtist.equals("")){ StandardWidget.currentArtist = metadataEditor.getString(MediaMetadataRetriever.METADATA_KEY_ALBUMARTIST,""); } if(StandardWidget.currentArtist==null||StandardWidget.currentArtist.equals("")){ StandardWidget.currentArtist = metadataEditor.getString(MediaMetadataRetriever.METADATA_KEY_AUTHOR,""); } sendBroadcast(new Intent(StandardWidget.WIDGET_UPDATE)); }
/** * Generates a new low-res icon given a high-res icon. */ private Bitmap generateLowResIcon(Bitmap icon, int lowResBackgroundColor) { if (lowResBackgroundColor == Color.TRANSPARENT) { return Bitmap.createScaledBitmap(icon, icon.getWidth() / LOW_RES_SCALE_FACTOR, icon.getHeight() / LOW_RES_SCALE_FACTOR, true); } else { Bitmap lowResIcon = Bitmap.createBitmap(icon.getWidth() / LOW_RES_SCALE_FACTOR, icon.getHeight() / LOW_RES_SCALE_FACTOR, Bitmap.Config.RGB_565); synchronized (this) { mLowResCanvas.setBitmap(lowResIcon); mLowResCanvas.drawColor(lowResBackgroundColor); mLowResCanvas.drawBitmap(icon, new Rect(0, 0, icon.getWidth(), icon.getHeight()), new Rect(0, 0, lowResIcon.getWidth(), lowResIcon.getHeight()), mLowResPaint); mLowResCanvas.setBitmap(null); } return lowResIcon; } }
@NonNull private BitmapDescriptor createClusterIcon(int clusterBucket) { @SuppressLint("InflateParams") TextView clusterIconView = (TextView) LayoutInflater.from(mContext) .inflate(R.layout.map_cluster_icon, null); clusterIconView.setBackground(createClusterBackground()); clusterIconView.setTextColor(mIconStyle.getClusterTextColor()); clusterIconView.setTextSize(TypedValue.COMPLEX_UNIT_PX, mIconStyle.getClusterTextSize()); clusterIconView.setText(getClusterIconText(clusterBucket)); clusterIconView.measure(View.MeasureSpec.UNSPECIFIED, View.MeasureSpec.UNSPECIFIED); clusterIconView.layout(0, 0, clusterIconView.getMeasuredWidth(), clusterIconView.getMeasuredHeight()); Bitmap iconBitmap = Bitmap.createBitmap(clusterIconView.getMeasuredWidth(), clusterIconView.getMeasuredHeight(), Bitmap.Config.ARGB_8888); Canvas canvas = new Canvas(iconBitmap); clusterIconView.draw(canvas); return BitmapDescriptorFactory.fromBitmap(iconBitmap); }
@Override protected Bitmap transform(BitmapPool pool, Bitmap toTransform, int outWidth, int outHeight) { if (toTransform == null) return null; int size = Math.min(toTransform.getWidth(), toTransform.getHeight()); int x = (toTransform.getWidth() - size) / 2; int y = (toTransform.getHeight() - size) / 2; Bitmap squared = Bitmap.createBitmap(toTransform, x, y, size, size); Bitmap result = pool.get(size, size, Bitmap.Config.ARGB_8888); if (result == null) { result = Bitmap.createBitmap(size, size, Bitmap.Config.ARGB_8888); } Canvas canvas = new Canvas(result); Paint paint = new Paint(); paint.setShader(new BitmapShader(squared, BitmapShader.TileMode.CLAMP, BitmapShader.TileMode.CLAMP)); paint.setAntiAlias(true); float r = size / 2f; canvas.drawCircle(r, r, r, paint); return result; }
@Test public void testDrawNewBitmap() { when(mPlatformBitmapFactory.createBitmap(anyInt(), anyInt(), any(Bitmap.Config.class))) .thenReturn(mBitmapRefererence); when(mBitmapFrameRenderer.renderFrame(anyInt(), any(Bitmap.class))).thenReturn(true); mBitmapAnimationBackend.drawFrame(mParentDrawable, mCanvas, 2); verify(mFrameListener).onDrawFrameStart(mBitmapAnimationBackend, 2); verify(mBitmapFrameCache).getCachedFrame(2); verify(mBitmapFrameCache).getBitmapToReuseForFrame(2, 0, 0); verify(mPlatformBitmapFactory).createBitmap(0, 0, Bitmap.Config.ARGB_8888); verify(mBitmapFrameRenderer).renderFrame(2, mBitmap); verify(mCanvas).drawBitmap(eq(mBitmap), eq(0f), eq(0f), any(Paint.class)); verifyFramePreparationStrategyCalled(2); verifyListenersAndCacheNotified(2, BitmapAnimationBackend.FRAME_TYPE_CREATED); assertReferencesClosed(); }
@Override protected void onPostExecute(Bitmap bitmap) { super.onPostExecute(bitmap); if (bitmap != null) { // Save image to cache. VolleyUtils.getBitmapCache().put(getCacheKey(cacheKey, urlsLength), bitmap); } if (!isCancelled()) { if (bitmap != null) { { image.setImageBitmap(bitmap); if (progressBar!=null) { progressBar.setVisibility(View.INVISIBLE); image.setVisibility(View.VISIBLE); } } } else setMultipleUserDefaultImg(); } }
/** * Constructor * @author leibing * @createTime 2017/3/2 * @lastModify 2017/3/2 * @param context ref * @return */ private JkImageLoader(Context context){ // init application conext mApplicationContext = context.getApplicationContext(); // init memory cache(one 8 of the max memory) int maxMemory = (int) (Runtime.getRuntime().maxMemory() / 1024); int cacheSize = maxMemory / 8; mMemoryCache = new LruCache<String, Bitmap>(cacheSize) { @Override protected int sizeOf(String key, Bitmap bitmap) { return bitmap.getRowBytes() * bitmap.getHeight() / 1024; } }; // init disk cache initDiskCache(); }
/** * 旋转bitmap * * @param origin bitmap * @param alpha 旋转角度 * @return 旋转后的bitmap */ public static Bitmap rotateBitmap(Bitmap origin, float alpha) { if (origin == null || origin.isRecycled()) { return null; } int width = origin.getWidth(); int height = origin.getHeight(); Matrix matrix = new Matrix(); matrix.setRotate(alpha); Bitmap newBM = Bitmap.createBitmap(origin, 0, 0, width, height, matrix, false); if (newBM.equals(origin)) { return newBM; } origin.recycle(); return newBM; }
@Test public void testLeastRecentlyUsedAttributeSetIsRemovedFirst() { final Bitmap leastRecentlyUsed = ShadowBitmap.createBitmap(100, 100, Bitmap.Config.ALPHA_8); final Bitmap other = ShadowBitmap.createBitmap(1000, 1000, Bitmap.Config.RGB_565); final Bitmap mostRecentlyUsed = ShadowBitmap.createBitmap(100, 100, Bitmap.Config.ARGB_8888); strategy.get(100, 100, Bitmap.Config.ALPHA_8); strategy.get(1000, 1000, Bitmap.Config.RGB_565); strategy.get(100, 100, Bitmap.Config.ARGB_8888); strategy.put(other); strategy.put(leastRecentlyUsed); strategy.put(mostRecentlyUsed); Bitmap removed = strategy.removeLast(); assertEquals( "Expected=" + strategy.logBitmap(leastRecentlyUsed) + " got=" + strategy.logBitmap(removed), leastRecentlyUsed, removed); }
/** * YUV420sp * * @param inputWidth * @param inputHeight * @param scaled * @return */ public static byte[] getYUV420sp(int inputWidth, int inputHeight, Bitmap scaled) { int[] argb = new int[inputWidth * inputHeight]; scaled.getPixels(argb, 0, inputWidth, 0, 0, inputWidth, inputHeight); /** * 需要转换成偶数的像素点,否则编码YUV420的时候有可能导致分配的空间大小不够而溢出。 */ int requiredWidth = inputWidth % 2 == 0 ? inputWidth : inputWidth + 1; int requiredHeight = inputHeight % 2 == 0 ? inputHeight : inputHeight + 1; int byteLength = requiredWidth * requiredHeight * 3 / 2; if (yuvs == null || yuvs.length < byteLength) { yuvs = new byte[byteLength]; } else { Arrays.fill(yuvs, (byte) 0); } encodeYUV420SP(yuvs, argb, inputWidth, inputHeight); scaled.recycle(); return yuvs; }
public Bitmap getBitmapFromView(String title, int dotBg) { LinearLayout llmarker = (LinearLayout) findViewById(R.id.ll_marker); TextView markerImageView = (TextView) findViewById(R.id.tv_title); markerImageView.setText(title); View dot = (View) findViewById(R.id.dot_marker); dot.setBackgroundResource(dotBg); llmarker.measure(View.MeasureSpec.UNSPECIFIED, View.MeasureSpec.UNSPECIFIED); Bitmap bitmap = Bitmap.createBitmap(llmarker.getMeasuredWidth(), llmarker.getMeasuredHeight(), Bitmap.Config.ARGB_8888); Canvas canvas = new Canvas(bitmap); llmarker.layout(0, 0, llmarker.getMeasuredWidth(), llmarker.getMeasuredHeight()); llmarker.draw(canvas); return bitmap; }
/** * 获取通知栏提醒所需的头像位图,只存内存缓存/磁盘缓存中取,如果没有则返回空,自动发起异步加载 * 注意:该方法在后台线程执行 */ public Bitmap getNotificationBitmapFromCache(String url) { if (TextUtils.isEmpty(url)) { return null; } final int imageSize = HeadImageView.DEFAULT_AVATAR_NOTIFICATION_ICON_SIZE; Bitmap cachedBitmap = null; try { cachedBitmap = Glide.with(context) .load(url) .asBitmap() .centerCrop() .into(imageSize, imageSize) .get(200, TimeUnit.MILLISECONDS); // 最大等待200ms } catch (Exception e) { e.printStackTrace(); } return cachedBitmap; }
public void closePhoto() { NotificationCenter.getInstance().removeObserver(this, NotificationCenter.messagesDeleted); NotificationCenter.getInstance().removeObserver(this, NotificationCenter.didCreatedNewDeleteTask); if (parentActivity == null) { return; } currentMessageObject = null; isVisible = false; AndroidUtilities.unlockOrientation(parentActivity); AndroidUtilities.runOnUIThread(new Runnable() { @Override public void run() { centerImage.setImageBitmap((Bitmap)null); } }); try { if (windowView.getParent() != null) { WindowManager wm = (WindowManager) parentActivity.getSystemService(Context.WINDOW_SERVICE); wm.removeView(windowView); } } catch (Exception e) { FileLog.e("tmessages", e); } }
/** * Generates an icon based on |text|. * * @param text The text to render the first character of on the icon. * @return The generated icon. */ public Bitmap generateIconForText(String text) { Bitmap icon = Bitmap.createBitmap(mIconWidthPx, mIconHeightPx, Bitmap.Config.ARGB_8888); Canvas canvas = new Canvas(icon); canvas.drawRoundRect(mBackgroundRect, mCornerRadiusPx, mCornerRadiusPx, mBackgroundPaint); String displayText = text.substring(0, 1).toUpperCase(Locale.getDefault()); float textWidth = mTextPaint.measureText(displayText); canvas.drawText( displayText, (mIconWidthPx - textWidth) / 2f, Math.round((Math.max(mIconHeightPx, mTextHeight) - mTextHeight) / 2.0f + mTextYOffset), mTextPaint); return icon; }
/** * Returns the in memory size of the given {@link Bitmap} in bytes. */ @TargetApi(Build.VERSION_CODES.KITKAT) public static int getBitmapByteSize(Bitmap bitmap) { // The return value of getAllocationByteCount silently changes for recycled bitmaps from the // internal buffer size to row bytes * height. To avoid random inconsistencies in caches, we // instead assert here. if (bitmap.isRecycled()) { throw new IllegalStateException("Cannot obtain size for recycled Bitmap: " + bitmap + "[" + bitmap.getWidth() + "x" + bitmap.getHeight() + "] " + bitmap.getConfig()); } if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) { // Workaround for KitKat initial release NPE in Bitmap, fixed in MR1. See issue #148. try { return bitmap.getAllocationByteCount(); } catch (NullPointerException e) { // Do nothing. } } return bitmap.getHeight() * bitmap.getRowBytes(); }
@Override public Bitmap getThumbForPhoto(MessageObject messageObject, TLRPC.FileLocation fileLocation, int index) { PhotoPickerPhotoCell cell = getCellForIndex(index); if (cell != null) { return cell.photoImage.getImageReceiver().getBitmap(); } return null; }
private Drawable a(String str, Context context) { Drawable createFromStream; IOException e; try { InputStream open = context.getApplicationContext().getAssets().open(str); if (open == null) { return null; } if (str.endsWith(".9.png")) { Bitmap decodeStream = BitmapFactory.decodeStream(open); if (decodeStream == null) { return null; } byte[] ninePatchChunk = decodeStream.getNinePatchChunk(); NinePatch.isNinePatchChunk(ninePatchChunk); return new NinePatchDrawable(decodeStream, ninePatchChunk, new Rect(), null); } createFromStream = Drawable.createFromStream(open, str); try { open.close(); return createFromStream; } catch (IOException e2) { e = e2; e.printStackTrace(); return createFromStream; } } catch (IOException e3) { IOException iOException = e3; createFromStream = null; e = iOException; e.printStackTrace(); return createFromStream; } }
/** * Constructs a BitmapContainer object. * @param bitmap The final bitmap (if it exists). * @param requestUrl The requested URL for this container. * @param cacheKey The cache key that identifies the requested URL for this container. */ public ImageContainer(Bitmap bitmap, String requestUrl, String cacheKey, ImageListener listener) { mBitmap = bitmap; mRequestUrl = requestUrl; mCacheKey = cacheKey; mListener = listener; }
public Bitmap get(String id){ try{ if(!cache.containsKey(id)) return null; return cache.get(id); }catch(NullPointerException ex){ ex.printStackTrace(); return null; } }
@SuppressWarnings("deprecation") private static Drawable bitmap2Drawable(Bitmap bm) { if (bm == null) { return null; } return new BitmapDrawable(bm); }
@Test public void imageBitmap() throws Exception { // Given ImageView imageView = mock(ImageView.class); Bitmap bitmap = mock(Bitmap.class); // When BlueTapeDsl .imageBitmap(bitmap) .bind(imageView); // Then verify(imageView).setImageBitmap(bitmap); }
public NoiseEffect(Bitmap bitmap, int grainFPS, float scale) { super(bitmap, 0, 0); shader = new BitmapShader(bitmap, Shader.TileMode.REPEAT, Shader.TileMode.REPEAT); matrix = new Matrix(); shader.setLocalMatrix(matrix); paint.setShader(shader); paint.setAlpha(144); paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SCREEN)); lastGrainOffset = System.currentTimeMillis(); this.grainFPS = grainFPS; this.scale=scale; }
private Bitmap generatePreview(Launcher launcher, WidgetItem item, Bitmap recycle, int previewWidth, int previewHeight) { if (item.widgetInfo != null) { return generateWidgetPreview(launcher, item.widgetInfo, previewWidth, recycle, null); } else { return generateShortcutPreview(launcher, item.activityInfo, previewWidth, previewHeight, recycle); } }
/** * Decodes image from URI into {@link Bitmap}. Image is scaled close to incoming {@linkplain ImageSize target size} * during decoding (depend on incoming parameters). * * @param decodingInfo Needed data for decoding image * @return Decoded bitmap * @throws IOException if some I/O exception occurs during image reading * @throws UnsupportedOperationException if image URI has unsupported scheme(protocol) */ @Override public Bitmap decode(ImageDecodingInfo decodingInfo) throws IOException { Bitmap decodedBitmap; ImageFileInfo imageInfo; InputStream imageStream = getImageStream(decodingInfo); if (imageStream == null) { L.e(ERROR_NO_IMAGE_STREAM, decodingInfo.getImageKey()); return null; } try { imageInfo = defineImageSizeAndRotation(imageStream, decodingInfo); imageStream = resetStream(imageStream, decodingInfo); Options decodingOptions = prepareDecodingOptions(imageInfo.imageSize, decodingInfo); decodedBitmap = BitmapFactory.decodeStream(imageStream, null, decodingOptions); } finally { IoUtils.closeSilently(imageStream); } if (decodedBitmap == null) { L.e(ERROR_CANT_DECODE_IMAGE, decodingInfo.getImageKey()); } else { decodedBitmap = considerExactScaleAndOrientatiton(decodedBitmap, decodingInfo, imageInfo.exif.rotation, imageInfo.exif.flipHorizontal); } return decodedBitmap; }
/** * 获取bitmap * * @param resId 资源id * @return bitmap */ public static Bitmap getBitmap(@DrawableRes final int resId) { Drawable drawable = ContextCompat.getDrawable(Utils.getApp(), resId); Canvas canvas = new Canvas(); Bitmap bitmap = Bitmap.createBitmap(drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight(), Bitmap.Config.ARGB_8888); canvas.setBitmap(bitmap); drawable.setBounds(0, 0, drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight()); drawable.draw(canvas); return bitmap; }
public void resizeImage(int width, int height) { if (image == null) { throw new NullPointerException("Please set an image before calling resizeImage()!"); } this.image = Bitmap.createScaledBitmap(image, width, height, false); invalidateImage(); }
@Test public void huntDecodesWhenNotInCache() throws Exception { Action action = mockAction(URI_KEY_1, URI_1, mockImageViewTarget()); TestableBitmapHunter hunter = new TestableBitmapHunter(picasso, dispatcher, cache, stats, action, bitmap); Bitmap result = hunter.hunt(); verify(cache).get(URI_KEY_1); verify(hunter.requestHandler).load(action.getRequest(), 0); assertThat(result).isEqualTo(bitmap); }