Java 类android.graphics.Bitmap 实例源码

项目:exciting-app    文件:FileUtil.java   
/**
 * 获取图片文件的宽高,宽高封装在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;
}
项目:AliZhiBoHao    文件:PushParamsActivity.java   
@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;
    }
}
项目:pc-android-controller-android    文件:ImageCompressUtil.java   
/**
         * @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;
        }
项目:Watermark    文件:MarkPresenter.java   
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;
}
项目:fast_face_android    文件:FaceDetTest.java   
@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();
}
项目:PicShow-zhaipin    文件:XCRoundImageView.java   
/**
 * 获取圆形图片方法
 * @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;


}
项目:GitHub    文件:GingerbreadPurgeableDecoder.java   
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();
    }
  }
}
项目:RunHDU    文件:ImageUtil.java   
/**
 * 对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;
}
项目:localcloud_fe    文件:CameraLauncher.java   
/**
 * 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;
}
项目:mvparms    文件:FastBlur.java   
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");
}
项目:TripBuyer    文件:AuthenticationActivity.java   
/**
 * 上传用户信息,首先上传头像,上传成功后赶回头像地址,然后上传其他信息
 */


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();

                }
            }
        });
    }
}
项目:androidgithub    文件:FriendListItem.java   
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);
        }
    }
}
项目:decoy    文件:BitmapDecoder.java   
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;
}
项目:musicwidget    文件:NotificationListenerKK.java   
@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));
}
项目:FlickLauncher    文件:IconCache.java   
/**
 * 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;
    }
}
项目:google-maps-clustering    文件:DefaultIconGenerator.java   
@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);
}
项目:event-me    文件:CircleTransform.java   
@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;
}
项目:GitHub    文件:BitmapAnimationBackendTest.java   
@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();
}
项目:chat-sdk-android-push-firebase    文件:MakeThreadImage.java   
@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();
    }
}
项目:JkImageLoader    文件:JkImageLoader.java   
/**
 * 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();
}
项目:Ocr-android    文件:BitmapUtils.java   
/**
 * 旋转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;
}
项目:GitHub    文件:AttributeStrategyTest.java   
@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);
}
项目:Mobike    文件:QrUtils.java   
/**
 * 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;
}
项目:Taxi-App-Android-XML    文件:Home.java   
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;
    }
项目:decoy    文件:ImageLoaderKit.java   
/**
 * 获取通知栏提醒所需的头像位图,只存内存缓存/磁盘缓存中取,如果没有则返回空,自动发起异步加载
 * 注意:该方法在后台线程执行
 */
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;
}
项目:airgram    文件:SecretPhotoViewer.java   
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);
    }
}
项目:chromium-for-android-56-debug-video    文件:RoundedIconGenerator.java   
/**
 * 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;
}
项目:GitHub    文件:Util.java   
/**
 * 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();
}
项目:airgram    文件:PhotoPickerActivity.java   
@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;
}
项目:letv    文件:AuthAgent.java   
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;
    }
}
项目:GitHub    文件:ImageLoader.java   
/**
 * 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;
}
项目:youth-health    文件:MemoryCache.java   
public Bitmap get(String id){
    try{
        if(!cache.containsKey(id))
            return null;
        return cache.get(id);
    }catch(NullPointerException ex){
        ex.printStackTrace();
        return null;
    }
}
项目:RLibrary    文件:ACache.java   
@SuppressWarnings("deprecation")
private static Drawable bitmap2Drawable(Bitmap bm) {
    if (bm == null) {
        return null;
    }
    return new BitmapDrawable(bm);
}
项目:BlueTape    文件:BlueTapeDslTest.java   
@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);
}
项目:Depth    文件:NoiseEffect.java   
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;
}
项目:FlickLauncher    文件:WidgetPreviewLoader.java   
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);
    }
}
项目:GitHub    文件:BaseImageDecoder.java   
/**
 * 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;
}
项目:GitHub    文件:ImageUtils.java   
/**
 * 获取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;
}
项目:empty-state-recyclerview    文件:ImageStateDisplay.java   
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();
}
项目:GitHub    文件:BitmapHunterTest.java   
@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);
}