Java Code Examples for android.graphics.Bitmap#getWidth()

The following examples show how to use android.graphics.Bitmap#getWidth() . These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may want to check out the right sidebar which shows the related API usage.
Example 1
Source Project: GlideBitmapPool   File: Util.java    License: Apache License 2.0 6 votes vote down vote up
public static boolean canUseForInBitmap(
        Bitmap candidate, BitmapFactory.Options targetOptions) {

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
        // From Android 4.4 (KitKat) onward we can re-use if the byte size of
        // the new bitmap is smaller than the reusable bitmap candidate
        // allocation byte count.
        int width = targetOptions.outWidth / targetOptions.inSampleSize;
        int height = targetOptions.outHeight / targetOptions.inSampleSize;
        int byteCount = width * height * getBytesPerPixel(candidate.getConfig());

        try {
            return byteCount <= candidate.getAllocationByteCount();
        } catch (NullPointerException e) {
            return byteCount <= candidate.getHeight() * candidate.getRowBytes();
        }
    }
    // On earlier versions, the dimensions must match exactly and the inSampleSize must be 1
    return candidate.getWidth() == targetOptions.outWidth
            && candidate.getHeight() == targetOptions.outHeight
            && targetOptions.inSampleSize == 1;
}
 
Example 2
Source Project: ImageSelector   File: ImageUtil.java    License: Apache License 2.0 6 votes vote down vote up
public static Bitmap zoomBitmap(Bitmap bm, int reqWidth, int reqHeight) {
    // 获得图片的宽高
    int width = bm.getWidth();
    int height = bm.getHeight();
    // 计算缩放比例
    float scaleWidth = ((float) reqWidth) / width;
    float scaleHeight = ((float) reqHeight) / height;
    float scale = Math.min(scaleWidth, scaleHeight);
    // 取得想要缩放的matrix参数
    Matrix matrix = new Matrix();
    matrix.postScale(scale, scale);
    // 得到新的图片
    Bitmap newbm = Bitmap.createBitmap(bm, 0, 0, width, height, matrix,
            true);
    return newbm;
}
 
Example 3
/**
 * 生成水印图片 水印在右下角
 *
 * @param src       the bitmap object you want proecss
 * @param watermark the water mark above the src
 * @return return a bitmap object ,if paramter's length is 0,return null
 */
public static Bitmap createWatermarkBitmap(Bitmap src, Bitmap watermark) {
    if (src == null) {
        return null;
    }

    int w = src.getWidth();
    int h = src.getHeight();
    int ww = watermark.getWidth();
    int wh = watermark.getHeight();
    // create the new blank bitmap
    Bitmap newb = Bitmap.createBitmap(w, h, Config.ARGB_8888);// 创建一个新的和SRC长度宽度一样的位图
    Canvas cv = new Canvas(newb);
    // draw src into
    cv.drawBitmap(src, 0, 0, null);// 在 0,0坐标开始画入src
    // draw watermark into
    cv.drawBitmap(watermark, w - ww + 5, h - wh + 5, null);// 在src的右下角画入水印
    // save all clip
    cv.save(Canvas.ALL_SAVE_FLAG);// 保存
    // store
    cv.restore();// 存储
    return newb;
}
 
Example 4
/**
 * 获得圆角图片的方法
 *
 * @param bitmap
 * @param roundPx 一般设成14
 * @return
 */
public static Bitmap getRoundedCornerBitmap(Bitmap bitmap, float roundPx) {

    Bitmap output = Bitmap.createBitmap(bitmap.getWidth(),
            bitmap.getHeight(), Config.ARGB_8888);
    Canvas canvas = new Canvas(output);

    final int color = 0xff424242;
    final Paint paint = new Paint();
    final Rect rect = new Rect(0, 0, bitmap.getWidth(), bitmap.getHeight());
    final RectF rectF = new RectF(rect);

    paint.setAntiAlias(true);
    canvas.drawARGB(0, 0, 0, 0);
    paint.setColor(color);
    canvas.drawRoundRect(rectF, roundPx, roundPx, paint);

    paint.setXfermode(new PorterDuffXfermode(Mode.SRC_IN));
    canvas.drawBitmap(bitmap, rect, rect, paint);

    return output;
}
 
Example 5
public Bitmap GetBitmapClippedCircle(Bitmap bitmap) {

      final int width = bitmap.getWidth();
      final int height = bitmap.getHeight();
      final Bitmap outputBitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);

      final Path path = new Path();
      path.addCircle((float) (width / 2), (float) (height / 2),
          (float) Math.min(width, (height / 2)), Path.Direction.CCW);

      final Canvas canvas = new Canvas(outputBitmap);
      canvas.clipPath(path);
      canvas.drawBitmap(bitmap, 0, 0, null);
      bitmap.recycle();
      return outputBitmap;
    }
 
Example 6
Source Project: UltimateAndroid   File: SignaturePad.java    License: Apache License 2.0 6 votes vote down vote up
public void setSignatureBitmap(Bitmap signature) {
    clear();
    ensureSignatureBitmap();

    RectF tempSrc = new RectF();
    RectF tempDst = new RectF();

    int dwidth = signature.getWidth();
    int dheight = signature.getHeight();
    int vwidth = getWidth();
    int vheight = getHeight();

    // Generate the required transform.
    tempSrc.set(0, 0, dwidth, dheight);
    tempDst.set(0, 0, vwidth, vheight);

    Matrix drawMatrix = new Matrix();
    drawMatrix.setRectToRect(tempSrc, tempDst, Matrix.ScaleToFit.CENTER);

    Canvas canvas = new Canvas(mSignatureBitmap);
    canvas.drawBitmap(signature, drawMatrix, null);
    setIsEmpty(false);
    invalidate();
}
 
Example 7
/**
 * 分割bitmap
 * 
 * @param bm
 *            源图片
 * @param xcount
 *            水平个数
 * @param ycount
 *            垂直个数
 * @return 小图片数组
 */
public static List<Bitmap> cutImage(Bitmap bm, int xcount, int ycount) {
    if (bm == null) {
        return null;
    }
    int width = bm.getWidth();
    int height = bm.getHeight();
    int imageWidth = width / xcount;
    int imageHeight = height / ycount;
    List<Bitmap> images = new ArrayList<Bitmap>(xcount * ycount);
    for (int i = 0; i < xcount; i++) {
        for (int j = 0; j < ycount; j++) {
            try {
                images.add(Bitmap.createBitmap(bm, i * imageWidth, j * imageHeight, imageWidth, imageHeight));
            } catch (Exception ex) {
                ex.printStackTrace();
            }
        }
    }
    return images;
}
 
Example 8
Source Project: Dashchan   File: RecaptchaReader.java    License: Apache License 2.0 5 votes vote down vote up
private static Bitmap[] splitImages(Bitmap image, int sizeX, int sizeY) {
	Bitmap[] images = new Bitmap[sizeX * sizeY];
	int width = image.getWidth() / sizeX;
	int height = image.getHeight() / sizeY;
	for (int y = 0; y < sizeY; y++) {
		for (int x = 0; x < sizeX; x++) {
			Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
			new Canvas(bitmap).drawBitmap(image, -x * width, -y * height, null);
			images[y * sizeX + x] = bitmap;
		}
	}
	return images;
}
 
Example 9
@Override
public void drawBackground(
        Canvas canvas, Paint paint,
        int left, int right, int top, int baseline, int bottom,
        CharSequence charSequence,
        int start, int end, int lineNum) {
    Bitmap bitmap= BitmapFactory.decodeResource(context.getResources(), R.drawable.rest);

    Rect mSrcRect = new Rect(left, top, bitmap.getWidth(), bitmap.getHeight());
    int width=(right-left)*3/4-(right-left)/2;
    Rect mDestRect = new Rect((right-left)*5/8, -width, (right-left)*7/8,0);
    canvas.drawBitmap(bitmap, mSrcRect, mDestRect, paint);
}
 
Example 10
@Override
/**
 * Keeps the size of the bitmap cached in member variables for faster access in {@link #onDraw(Canvas)} ,
 * but without keeping another reference to the {@link Bitmap}
 */
public void setImageBitmap (Bitmap bm) {
    mBitmapWidth = bm.getWidth();
    mBitmapHeight = bm.getHeight();
    super.setImageBitmap(bm);
}
 
Example 11
/**
 * Read bytes.
 *
 * @param uri      the uri
 * @param resolver the resolver
 * @return the byte[]
 * @throws IOException Signals that an I/O exception has occurred.
 */
private static byte[] readBytes(Uri uri, ContentResolver resolver, boolean thumbnail)
        throws IOException {
    // this dynamically extends to take the bytes you read
    InputStream inputStream = resolver.openInputStream(uri);
    ByteArrayOutputStream byteBuffer = new ByteArrayOutputStream();

    if (!thumbnail) {
        // this is storage overwritten on each iteration with bytes
        int bufferSize = 1024;
        byte[] buffer = new byte[bufferSize];

        // we need to know how may bytes were read to write them to the
        // byteBuffer
        int len = 0;
        while ((len = inputStream.read(buffer)) != -1) {
            byteBuffer.write(buffer, 0, len);
        }
    } else {
        Bitmap imageBitmap = BitmapFactory.decodeStream(inputStream);
        int thumb_width = imageBitmap.getWidth() / 2;
        int thumb_height = imageBitmap.getHeight() / 2;
        if (thumb_width > THUMBNAIL_SIZE) {
            thumb_width = THUMBNAIL_SIZE;
        }
        if (thumb_width == THUMBNAIL_SIZE) {
            thumb_height = ((imageBitmap.getHeight() / 2) * THUMBNAIL_SIZE)
                    / (imageBitmap.getWidth() / 2);
        }
        imageBitmap = Bitmap.createScaledBitmap(imageBitmap, thumb_width, thumb_height, false);
        imageBitmap.compress(Bitmap.CompressFormat.JPEG, 100, byteBuffer);
    }
    // and then we can return your byte array.
    return byteBuffer.toByteArray();
}
 
Example 12
Source Project: videocreator   File: BitmapUtil.java    License: Apache License 2.0 5 votes vote down vote up
/**
     * 从图片加载到另一张图片
     *
     * @param bitmap
     * @param bitmap_src
     * @return
     */
    public static Bitmap loadFromBitmap(Bitmap bitmap, Bitmap bitmap_src, boolean clearBmp) {
        if (clearBmp)
            bitmap.eraseColor(Color.TRANSPARENT);
//		bitmap_src = zoomBitmap(bitmap_src, bitmap.getWidth(), bitmap.getHeight());
//		loadFromBytes(bitmap, getBytes(bitmap_src));
        Canvas canvas = new Canvas(bitmap);
        canvas.setDrawFilter(new PaintFlagsDrawFilter(0, Paint.ANTI_ALIAS_FLAG | Paint.FILTER_BITMAP_FLAG));
        float rw = (float) bitmap.getWidth() / bitmap_src.getWidth();
        float rh = (float) bitmap.getHeight() / bitmap_src.getHeight();
        canvas.scale(rw, rh);
        canvas.drawBitmap(bitmap_src, 0, 0, null);
        return bitmap;
    }
 
Example 13
@Override
public Bitmap transform(Bitmap source) {

    int size = Math.min(source.getWidth(), source.getHeight());

    int x = (source.getWidth() - size) / 2;
    int y = (source.getHeight() - size) / 2;

    Bitmap squaredBtimap = Bitmap.createBitmap(source, x, y, size, size);
    if (squaredBtimap != source){
        source.recycle();
    }

    Bitmap bitmap = Bitmap.createBitmap(size, size, source.getConfig());

    Canvas canvas = new Canvas(bitmap);

    Paint avatarPaint = new Paint();
    BitmapShader shader = new BitmapShader(squaredBtimap, BitmapShader.TileMode.CLAMP, BitmapShader.TileMode.CLAMP);
    avatarPaint.setShader(shader);

    Paint outlinePaint = new Paint();
    outlinePaint.setColor(Color.WHITE);
    outlinePaint.setStyle(Paint.Style.STROKE);
    outlinePaint.setStrokeWidth(STROKE_WIDTH);
    outlinePaint.setAntiAlias(true);

    float r = size / 2f;
    canvas.drawCircle(r, r, r, avatarPaint);
    canvas.drawCircle(r, r, r - STROKE_WIDTH / 2, outlinePaint);

    squaredBtimap.recycle();
    return bitmap;


}
 
Example 14
Source Project: kAndroid   File: PictureMergeManager.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 把两个位图覆盖合成为一个位图,上下拼接
 * isBaseMax 是否以高度大的位图为准,true则小图等比拉伸,false则大图等比压缩
 *
 * @return
 */
public Bitmap mergeBitmap_TB(Bitmap topBitmap, Bitmap bottomBitmap, boolean isBaseMax) {
    if (topBitmap == null || topBitmap.isRecycled() || bottomBitmap == null || bottomBitmap.isRecycled()) {
        Log.i("错误", "topBitmap=" + topBitmap + ";bottomBitmap=" + bottomBitmap);
        return null;
    }
    int width = 0;
    if (isBaseMax) {
        width = topBitmap.getWidth() > bottomBitmap.getWidth() ? topBitmap.getWidth() : bottomBitmap.getWidth();
    } else {
        width = topBitmap.getWidth() < bottomBitmap.getWidth() ? topBitmap.getWidth() : bottomBitmap.getWidth();
    }
    Bitmap tempBitmapT = topBitmap;
    Bitmap tempBitmapB = bottomBitmap;
    if (topBitmap.getWidth() != width) {
        tempBitmapT = Bitmap.createScaledBitmap(topBitmap, width, (int) (topBitmap.getHeight() * 1f / topBitmap.getWidth() * width), false);
    } else if (bottomBitmap.getWidth() != width) {
        tempBitmapB = Bitmap.createScaledBitmap(bottomBitmap, width, (int) (bottomBitmap.getHeight() * 1f / bottomBitmap.getWidth() * width), false);
    }

    int height = tempBitmapT.getHeight() + tempBitmapB.getHeight();

    Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
    Canvas canvas = new Canvas(bitmap);

    Rect topRect = new Rect(0, 0, tempBitmapT.getWidth(), tempBitmapT.getHeight());
    Rect bottomRect = new Rect(0, 0, tempBitmapB.getWidth(), tempBitmapB.getHeight());

    Rect bottomRectT = new Rect(0, tempBitmapT.getHeight(), width, height);

    canvas.drawBitmap(tempBitmapT, topRect, topRect, null);
    canvas.drawBitmap(tempBitmapB, bottomRect, bottomRectT, null);
    return bitmap;
}
 
Example 15
private void performReplace(String oldKey, String newKey) {
    BitmapDrawable b = memCache.get(oldKey);
    replacedBitmaps.put(oldKey, newKey);
    if (b != null) {
        BitmapDrawable oldBitmap = memCache.get(newKey);
        boolean dontChange = false;
        if (oldBitmap != null && oldBitmap.getBitmap() != null && b.getBitmap() != null) {
            Bitmap oldBitmapObject = oldBitmap.getBitmap();
            Bitmap newBitmapObject = b.getBitmap();
            if (oldBitmapObject.getWidth() > newBitmapObject.getWidth() || oldBitmapObject.getHeight() > newBitmapObject.getHeight()) {
                dontChange = true;
            }
        }
        if (!dontChange) {
            ignoreRemoval = oldKey;
            memCache.remove(oldKey);
            memCache.put(newKey, b);
            ignoreRemoval = null;
        } else {
            memCache.remove(oldKey);
        }
    }
    Integer val = bitmapUseCounts.get(oldKey);
    if (val != null) {
        bitmapUseCounts.put(newKey, val);
        bitmapUseCounts.remove(oldKey);
    }
}
 
Example 16
/**
 * Adds a shadow to a Bitmap.
 * <p>
 * TODO: Make this return Drawable for our use case.
 *
 * @param drawable  Drawable that should be used as the foreground layer
 *                  of the shadow.
 * @param dstHeight Height of the returned bitmap.
 * @param dstWidth  Width of the returned bitmap.
 * @param color     Colour of the drawn shadow.
 * @param size      Size of the drawn shadow.
 * @param dx        Shadow x direction.
 * @param dy        Shadow y direction.
 *
 * @return Bitmap with resulting shadow.
 *
 * @author schwiz (https://stackoverflow.com/a/24579764)
 */
private static Bitmap addShadow(final Drawable drawable, final int dstHeight, final int dstWidth, int color, int size, float dx, float dy) {
    final Bitmap bm = Bitmap.createBitmap(drawable.getIntrinsicWidth(),
            drawable.getIntrinsicHeight(), Bitmap.Config.ARGB_8888);
    final Canvas canvas = new Canvas(bm);
    drawable.setBounds(0, 0, canvas.getWidth(), canvas.getHeight());
    drawable.draw(canvas);

    final Bitmap mask = Bitmap.createBitmap(dstWidth, dstHeight, Bitmap.Config.ALPHA_8);

    final Matrix scaleToFit = new Matrix();
    final RectF src = new RectF(0, 0, bm.getWidth(), bm.getHeight());
    final RectF dst = new RectF(0, 0, dstWidth - dx, dstHeight - dy);
    scaleToFit.setRectToRect(src, dst, Matrix.ScaleToFit.FILL);

    final Matrix dropShadow = new Matrix(scaleToFit);
    dropShadow.postTranslate(dx, dy);

    final Canvas maskCanvas = new Canvas(mask);
    final Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
    maskCanvas.drawBitmap(bm, scaleToFit, paint);
    paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_OUT));
    maskCanvas.drawBitmap(bm, dropShadow, paint);

    final BlurMaskFilter filter = new BlurMaskFilter(size, BlurMaskFilter.Blur.SOLID);
    paint.reset();
    paint.setAntiAlias(true);
    paint.setColor(color);
    paint.setMaskFilter(filter);
    paint.setFilterBitmap(true);

    final Bitmap ret = Bitmap.createBitmap(dstWidth, dstHeight, Bitmap.Config.ARGB_8888);
    final Canvas retCanvas = new Canvas(ret);
    retCanvas.drawBitmap(mask, 0, 0, paint);
    retCanvas.drawBitmap(bm, scaleToFit, null);
    mask.recycle();
    return ret;
}
 
Example 17
Source Project: video-player   File: ThumbnailUtils.java    License: MIT License 5 votes vote down vote up
public static Bitmap extractThumbnail(Bitmap source, int width, int height, int options) {
  if (source == null)
    return null;

  float scale;
  if (source.getWidth() < source.getHeight())
    scale = width / (float) source.getWidth();
  else
    scale = height / (float) source.getHeight();
  Matrix matrix = new Matrix();
  matrix.setScale(scale, scale);
  Bitmap thumbnail = transform(matrix, source, width, height, OPTIONS_SCALE_UP | options);
  return thumbnail;
}
 
Example 18
/**
 * @returns Whether |icon| is suitable as the media image, i.e. bigger than the minimal size.
 * @param icon The icon to be checked.
 */
public static boolean isBitmapSuitableAsMediaImage(Bitmap icon) {
    return icon != null && icon.getWidth() >= MINIMAL_MEDIA_IMAGE_SIZE_PX
            && icon.getHeight() >= MINIMAL_MEDIA_IMAGE_SIZE_PX;
}
 
Example 19
public static TLRPC.PhotoSize scaleAndSaveImage(TLRPC.PhotoSize photoSize, Bitmap bitmap, Bitmap.CompressFormat compressFormat, float maxWidth, float maxHeight, int quality, boolean cache, int minWidth, int minHeight, boolean forceCacheDir) {
    if (bitmap == null) {
        return null;
    }
    float photoW = bitmap.getWidth();
    float photoH = bitmap.getHeight();
    if (photoW == 0 || photoH == 0) {
        return null;
    }
    boolean scaleAnyway = false;
    float scaleFactor = Math.max(photoW / maxWidth, photoH / maxHeight);
    if (minWidth != 0 && minHeight != 0 && (photoW < minWidth || photoH < minHeight)) {
        if (photoW < minWidth && photoH > minHeight) {
            scaleFactor = photoW / minWidth;
        } else if (photoW > minWidth && photoH < minHeight) {
            scaleFactor = photoH / minHeight;
        } else {
            scaleFactor = Math.max(photoW / minWidth, photoH / minHeight);
        }
        scaleAnyway = true;
    }
    int w = (int) (photoW / scaleFactor);
    int h = (int) (photoH / scaleFactor);
    if (h == 0 || w == 0) {
        return null;
    }

    try {
        return scaleAndSaveImageInternal(photoSize, bitmap, compressFormat, w, h, photoW, photoH, scaleFactor, quality, cache, scaleAnyway, forceCacheDir);
    } catch (Throwable e) {
        FileLog.e(e);
        ImageLoader.getInstance().clearMemory();
        System.gc();
        try {
            return scaleAndSaveImageInternal(photoSize, bitmap, compressFormat, w, h, photoW, photoH, scaleFactor, quality, cache, scaleAnyway, forceCacheDir);
        } catch (Throwable e2) {
            FileLog.e(e2);
            return null;
        }
    }
}
 
Example 20
/**
 * The real guts of parseNetworkResponse. Broken out for readability.
 */
private Response<Bitmap> doParse(NetworkResponse response) {
    byte[] data = response.data;
    BitmapFactory.Options decodeOptions = new BitmapFactory.Options();
    Bitmap bitmap = null;
    if (mMaxWidth == 0 && mMaxHeight == 0) {
        decodeOptions.inPreferredConfig = mDecodeConfig;
        bitmap = BitmapFactory.decodeByteArray(data, 0, data.length, decodeOptions);
    } else {
        // If we have to resize this image, first get the natural bounds.
        decodeOptions.inJustDecodeBounds = true;
        BitmapFactory.decodeByteArray(data, 0, data.length, decodeOptions);
        int actualWidth = decodeOptions.outWidth;
        int actualHeight = decodeOptions.outHeight;

        // Then compute the dimensions we would ideally like to decode to.
        int desiredWidth = getResizedDimension(mMaxWidth, mMaxHeight,
                actualWidth, actualHeight);
        int desiredHeight = getResizedDimension(mMaxHeight, mMaxWidth,
                actualHeight, actualWidth);

        // Decode to the nearest power of two scaling factor.
        decodeOptions.inJustDecodeBounds = false;
        // TODO(ficus): Do we need this or is it okay since API 8 doesn't support it?
        // decodeOptions.inPreferQualityOverSpeed = PREFER_QUALITY_OVER_SPEED;
        decodeOptions.inSampleSize =
            findBestSampleSize(actualWidth, actualHeight, desiredWidth, desiredHeight);
        Bitmap tempBitmap =
            BitmapFactory.decodeByteArray(data, 0, data.length, decodeOptions);

        // If necessary, scale down to the maximal acceptable size.
        if (tempBitmap != null && (tempBitmap.getWidth() > desiredWidth ||
                tempBitmap.getHeight() > desiredHeight)) {
            bitmap = Bitmap.createScaledBitmap(tempBitmap,
                    desiredWidth, desiredHeight, true);
            tempBitmap.recycle();
        } else {
            bitmap = tempBitmap;
        }
    }

    if (bitmap == null) {
        return Response.error(new ParseError(response));
    } else {
        return Response.success(bitmap, HttpHeaderParser.parseCacheHeaders(response));
    }
}