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

The following examples show how to use android.graphics.Bitmap#createScaledBitmap() . 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 check out the related API usage on the sidebar.
Example 1
Source File: ImageDownloadTask.java    From mlkit-material-android with Apache License 2.0 7 votes vote down vote up
@Override
@Nullable
protected Bitmap doInBackground(String... urls) {
  if (TextUtils.isEmpty(urls[0])) {
    return null;
  }

  Bitmap bitmap = null;
  try {
    InputStream inputStream = new URL(urls[0]).openStream();
    bitmap = BitmapFactory.decodeStream(inputStream);
    inputStream.close();
  } catch (Exception e) {
    Log.e(TAG, "Image download failed: " + urls[0]);
  }

  if (bitmap != null && bitmap.getWidth() > maxImageWidth) {
    int dstHeight = (int) ((float) maxImageWidth / bitmap.getWidth() * bitmap.getHeight());
    bitmap = Bitmap.createScaledBitmap(bitmap, maxImageWidth, dstHeight, /* filter= */ false);
  }
  return bitmap;
}
 
Example 2
Source File: EmojiPageBitmap.java    From deltachat-android with GNU General Public License v3.0 6 votes vote down vote up
private Bitmap loadPage() throws IOException {
  if (bitmapReference != null && bitmapReference.get() != null) return bitmapReference.get();


  float                 scale        = decodeScale;
  AssetManager          assetManager = context.getAssets();
  InputStream           assetStream  = assetManager.open(model.getSprite());
  BitmapFactory.Options options      = new BitmapFactory.Options();

  if (Util.isLowMemory(context)) {
    Log.i(TAG, "Low memory detected. Changing sample size.");
    options.inSampleSize = 2;
    scale = decodeScale * 2;
  }

  Stopwatch stopwatch = new Stopwatch(model.getSprite());
  Bitmap    bitmap    = BitmapFactory.decodeStream(assetStream, null, options);
  stopwatch.split("decode");

  Bitmap scaledBitmap = Bitmap.createScaledBitmap(bitmap, (int)(bitmap.getWidth() * scale), (int)(bitmap.getHeight() * scale), true);
  stopwatch.split("scale");
  stopwatch.stop(TAG);

  bitmapReference = new SoftReference<>(scaledBitmap);
  Log.i(TAG, "onPageLoaded(" + model.getSprite() + ")  originalByteCount: " + bitmap.getByteCount()
                                                  + "  scaledByteCount: "   + scaledBitmap.getByteCount()
                                                  + "  scaledSize: "        + scaledBitmap.getWidth() + "x" + scaledBitmap.getHeight());
  return scaledBitmap;
}
 
Example 3
Source File: FileBackend.java    From Conversations with GNU General Public License v3.0 6 votes vote down vote up
private Bitmap resize(final Bitmap originalBitmap, int size) throws IOException {
    int w = originalBitmap.getWidth();
    int h = originalBitmap.getHeight();
    if (w <= 0 || h <= 0) {
        throw new IOException("Decoded bitmap reported bounds smaller 0");
    } else if (Math.max(w, h) > size) {
        int scalledW;
        int scalledH;
        if (w <= h) {
            scalledW = Math.max((int) (w / ((double) h / size)), 1);
            scalledH = size;
        } else {
            scalledW = size;
            scalledH = Math.max((int) (h / ((double) w / size)), 1);
        }
        final Bitmap result = Bitmap.createScaledBitmap(originalBitmap, scalledW, scalledH, true);
        if (!originalBitmap.isRecycled()) {
            originalBitmap.recycle();
        }
        return result;
    } else {
        return originalBitmap;
    }
}
 
Example 4
Source File: WeichatShareImpl.java    From ChinaShare with MIT License 6 votes vote down vote up
private Bitmap getBitmapThumb(final String shareImageUrl) {
    Bitmap thumb = null;
    if (TextUtils.isEmpty(shareImageUrl)) {
        thumb = BitmapFactory.decodeResource(mActivity.getResources(), ShareManager.getDefShareImageUrlId());
        thumb = compressImage(thumb, 32);
    } else {
        try {
            Bitmap bmp = BitmapFactory.decodeStream(new URL(shareImageUrl).openStream());
            thumb = Bitmap.createScaledBitmap(bmp, THUMB_SIZE, THUMB_SIZE, true);
        }catch (Exception e){
            e.printStackTrace();
            thumb = null;
        }
    }
    if (thumb == null)
        thumb = BitmapFactory.decodeResource(mActivity.getResources(), R.drawable.ic_launcher);
    return thumb;
}
 
Example 5
Source File: PointerView.java    From AndroidStudyDemo with GNU General Public License v2.0 5 votes vote down vote up
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
    setMeasuredDimension(measureWidth(widthMeasureSpec), measureWidth(heightMeasureSpec));
    x = getMeasuredWidth();
    y = getMeasuredHeight();
    mFinalPointerBitmap = Bitmap.createScaledBitmap(mPointerBitmap, x, y, true);
}
 
Example 6
Source File: MediaUtils.java    From IdealMedia with Apache License 2.0 5 votes vote down vote up
public static Bitmap modifyTrackCellArtworkBitmap(Bitmap source){
    if (source == null)
        return null;

    int w = source.getWidth();
    int h = source.getHeight();

    Bitmap scaled = Bitmap.createScaledBitmap(source, w, h, true);

    w = scaled.getWidth();
    h = scaled.getHeight();

    Bitmap overlay = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888);

    Canvas canvas = new Canvas(overlay);
    final Paint paint = new Paint();

    canvas.drawBitmap(scaled, 0, 0, null);

    Shader shader = new LinearGradient(
            0, 0, h, 0,
            0x00FFFFFF, 0x77FFFFFF,
            Shader.TileMode.CLAMP
    );

    paint.setShader(shader);
    paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_IN));

    canvas.drawRect(0, 0, w, h, paint);

    return overlay;
}
 
Example 7
Source File: BlurPostprocessor.java    From fresco-processors with Apache License 2.0 5 votes vote down vote up
@Override public void process(Bitmap dest, Bitmap source) {

    int width = source.getWidth();
    int height = source.getHeight();
    int scaledWidth = width / sampling;
    int scaledHeight = height / sampling;

    Bitmap blurredBitmap = Bitmap.createBitmap(scaledWidth, scaledHeight, Bitmap.Config.ARGB_8888);

    Canvas canvas = new Canvas(blurredBitmap);
    canvas.scale(1 / (float) sampling, 1 / (float) sampling);
    Paint paint = new Paint();
    paint.setFlags(Paint.FILTER_BITMAP_FLAG);
    canvas.drawBitmap(source, 0, 0, paint);

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) {
      try {
        blurredBitmap = RSBlur.blur(context, blurredBitmap, radius);
      } catch (android.renderscript.RSRuntimeException e) {
        blurredBitmap = FastBlur.blur(blurredBitmap, radius, true);
      }
    } else {
      blurredBitmap = FastBlur.blur(blurredBitmap, radius, true);
    }

    Bitmap scaledBitmap =
        Bitmap.createScaledBitmap(blurredBitmap, dest.getWidth(), dest.getHeight(), true);
    blurredBitmap.recycle();

    super.process(dest, scaledBitmap);
  }
 
Example 8
Source File: Camera2BasicFragment.java    From Cam2Caption with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
float[] Preprocess(Bitmap imBitmap){
    imBitmap = Bitmap.createScaledBitmap(imBitmap, IMAGE_SIZE, IMAGE_SIZE, true);
    int[] intValues = new int[IMAGE_SIZE * IMAGE_SIZE];
    float[] floatValues = new float[IMAGE_SIZE * IMAGE_SIZE * 3];

    imBitmap.getPixels(intValues, 0, IMAGE_SIZE, 0, 0, IMAGE_SIZE, IMAGE_SIZE);

    for (int i = 0; i < intValues.length; ++i) {
        final int val = intValues[i];
        floatValues[i * 3] = ((float)((val >> 16) & 0xFF))/255;//R
        floatValues[i * 3 + 1] = ((float)((val >> 8) & 0xFF))/255;//G
        floatValues[i * 3 + 2] = ((float)((val & 0xFF)))/255;//B
    }
    return floatValues;
}
 
Example 9
Source File: SlotMachineActivity.java    From BigApp_Discuz_Android with Apache License 2.0 5 votes vote down vote up
/**
 * Loads image from resources
 */
private Bitmap loadImage(int id) {
    Bitmap bitmap = BitmapFactory.decodeResource(context.getResources(), id);
    Bitmap scaled = Bitmap.createScaledBitmap(bitmap, IMAGE_WIDTH, IMAGE_HEIGHT, true);
    bitmap.recycle();
    return scaled;
}
 
Example 10
Source File: CommonFunctions.java    From Expert-Android-Programming with MIT License 5 votes vote down vote up
public static Bitmap scaleDownBitmap(Bitmap realImage, float maxImageSize,
                               boolean filter) {
    float ratio = Math.min(
            (float) maxImageSize / realImage.getWidth(),
            (float) maxImageSize / realImage.getHeight());
    int width = Math.round((float) ratio * realImage.getWidth());
    int height = Math.round((float) ratio * realImage.getHeight());

    Bitmap newBitmap = Bitmap.createScaledBitmap(realImage, width,
            height, filter);
    return newBitmap;
}
 
Example 11
Source File: onImageCenter.java    From ArcProgressBar with Apache License 2.0 5 votes vote down vote up
@Override
public void draw(Canvas canvas, RectF rectF, float x, float y, float storkeWidth, int progress) {

    if(mTarget == null){
        mTarget = Bitmap.createScaledBitmap(mBmp, (int) (rectF.right - storkeWidth * 2), (int) (rectF.right - storkeWidth * 2), false);
    }

    Bitmap target = Bitmap.createBitmap(mTarget, 0, 0, mTarget.getWidth(), mTarget.getHeight());
    float sx = x - target.getWidth() / 2;
    float sy = y - target.getHeight() / 2;
    Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
    canvas.drawCircle(x, y, (rectF.right - storkeWidth * 2) / 2, paint);
    paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN));
    canvas.drawBitmap(target, sx, sy, paint);
}
 
Example 12
Source File: ProfilePictureActivity.java    From kute with Apache License 2.0 5 votes vote down vote up
public Bitmap getResizedBitmap(Bitmap image, int maxSize) {
    int width = image.getWidth();
    int height = image.getHeight();

    float bitmapRatio = (float) width / (float) height;
    if (bitmapRatio > 0) {
        width = maxSize;
        height = (int) (width / bitmapRatio);
    } else {
        height = maxSize;
        width = (int) (height * bitmapRatio);
    }
    return Bitmap.createScaledBitmap(image, width, height, true);
}
 
Example 13
Source File: BaseDialog.java    From AssistantBySDK with Apache License 2.0 5 votes vote down vote up
private void shareToWechat(boolean timeline) {
    if (isPkgInstalled("com.tencent.mm")) {
        // 初始化一个WXTextObject对象
        Bitmap bmp = BitmapFactory.decodeResource(mContext.getResources(), R.drawable.ic_launcher);
        //WXImageObject imgObj = new WXImageObject(bmp);

        WXWebpageObject webObj = new WXWebpageObject();
        webObj.webpageUrl = shareLink;


        WXMediaMessage msg = new WXMediaMessage();
        msg.mediaObject = webObj;

        Bitmap thumbBmp = Bitmap.createScaledBitmap(bmp, 150, 150, true);
        bmp.recycle();
        msg.thumbData = Util.bmpToByteArray(thumbBmp, true);  // 设置缩略图
        msg.description = mContext.getResources().getString(R.string.shareDescription);
        msg.title = shareText;

        SendMessageToWX.Req req = new SendMessageToWX.Req();
        req.transaction = buildTransaction("webpage");
        req.message = msg;

        req.scene = timeline ? SendMessageToWX.Req.WXSceneTimeline : SendMessageToWX.Req.WXSceneSession;

        // 调用api接口发送数据到微信
        wAPI.sendReq(req);
    } else {
        new CommonDialog(getActivity(), "温馨提示", "未检测到“微信”应用", "确定").show();
    }
}
 
Example 14
Source File: BitmapHelper.java    From LyricHere with Apache License 2.0 4 votes vote down vote up
public static Bitmap scaleBitmap(Bitmap src, int maxWidth, int maxHeight) {
    double scaleFactor = Math.min(
            ((double) maxWidth) / src.getWidth(), ((double) maxHeight) / src.getHeight());
    return Bitmap.createScaledBitmap(src,
            (int) (src.getWidth() * scaleFactor), (int) (src.getHeight() * scaleFactor), false);
}
 
Example 15
Source File: ImageLoaderUtils.java    From q-municate-android with Apache License 2.0 4 votes vote down vote up
private Bitmap scaleBitmap(Bitmap origBitmap, int width, int height) {
    float scale = Math.min(((float) width) / ((float) origBitmap.getWidth()),
            ((float) height) / ((float) origBitmap.getHeight()));
    return Bitmap.createScaledBitmap(origBitmap, (int) (((float) origBitmap.getWidth()) * scale),
            (int) (((float) origBitmap.getHeight()) * scale), false);
}
 
Example 16
Source File: CircleImageView.java    From MyHearts with Apache License 2.0 4 votes vote down vote up
/**
 * 绘制
 * @param canvas
 */
@Override
protected void onDraw(Canvas canvas) {
    //加载图片
    loadImage();

    if (image != null) {
        //拿到最小的值
        int min = Math.min(viewWidth, viewHeigth);

        int circleCenter = min / 2;

        image = Bitmap.createScaledBitmap(image, min, min, false);

        canvas.drawCircle(circleCenter + outCircleWidth, circleCenter + outCircleWidth, circleCenter + outCircleColor, paint);

        canvas.drawBitmap(createCircleBitmap(image, min), outCircleWidth, outCircleWidth, null);
    }


}
 
Example 17
Source File: BlurTool.java    From incubator-weex-playground with Apache License 2.0 4 votes vote down vote up
/**
 * radius in [0,10]
 * */
@NonNull
@SuppressWarnings("unused")
public static Bitmap blur(@NonNull Bitmap originalImage, int radius) {
    long start = System.currentTimeMillis();
    radius = Math.min(10, Math.max(0,radius));//[0,10]
    if(radius == 0) {
        return originalImage;
    }
    int width = originalImage.getWidth();
    int height = originalImage.getHeight();

    if(width <= 0 || height <= 0) {
        return originalImage;
    }

    double sampling = calculateSampling(radius);
    int retryTimes = 3;
    Bitmap sampledImage = Bitmap.createScaledBitmap(originalImage,(int)(sampling*width),(int)(sampling*height),true);
    for(int i = 0; i < retryTimes; i++) {
        try {
            if(radius == 0) {
                return originalImage;
            }
            double s = calculateSampling(radius);
            if(s != sampling) {
                sampling = s;
                sampledImage = Bitmap.createScaledBitmap(originalImage,(int)(sampling*width),(int)(sampling*height),true);
            }

            Bitmap result = stackBlur(sampledImage,radius);
            return result;
        }catch (Exception e) {
            WXLogUtils.e(TAG, "thrown exception when blurred image(times = " + i + "),"+ e.getMessage());
            radius -= 1;
            radius = Math.max(0,radius);
        }
    }
    WXLogUtils.d(TAG, "elapsed time on blurring image(radius:"+ radius + ",sampling: " + sampling + "): " + (System.currentTimeMillis() - start) + "ms");
    return originalImage;
}
 
Example 18
Source File: Yolov3TinyDrawRectTest.java    From pasm-yolov3-Android with GNU General Public License v3.0 4 votes vote down vote up
@Test
    public void drawImage() throws IOException {
        OpenCVLoader.initAsync(OpenCVLoader.OPENCV_VERSION, appContext, mLoaderCallback);

        YoloV3Classifier detector = (YoloV3Classifier) YoloV3Classifier.create(
                appContext.getAssets(),
                TINY_YOLO_MODEL_FILE,
                TINY_YOLO_INPUT_SIZE,
                TINY_YOLO_INPUT_NAME,
                TINY_YOLO_OUTPUT_NAMES,
                TINY_YOLO_BLOCK_SIZE,
                0);

        checkPermissions();
//        Bitmap loadedImage = getBitmapFromTestAssets(SAMPLE_IMG);

        Context testContext = InstrumentationRegistry.getInstrumentation().getContext();
        AssetManager assetManager = testContext.getAssets();

        String pathToImages = "images";
//        String pathToImages = SAMPLE_IMG; // change pathToImages to this for single image

        String[] list = assetManager.list(pathToImages);

        for (int i = 0; i < list.length; i++) {
            if(list[i].endsWith(".jpg")) {
                Bitmap loadedImage = getBitmapFromTestAssets(list[i], pathToImages);

                Bitmap redimBitmap = Bitmap.createScaledBitmap(loadedImage, TINY_YOLO_INPUT_SIZE, TINY_YOLO_INPUT_SIZE, false);

                long start = System.currentTimeMillis();
                List<Classifier.Recognition> recognitions = detector.recognizeImage(redimBitmap);
                long end = System.currentTimeMillis();
                Log.i(TAG, "execution time = " + (end-start));

                Log.i(TAG, "yolov3 recognitions = " + recognitions);

                ImageProcessor processor = new ImageProcessor(testContext, detector.getLabels());
                processor.loadImage(loadedImage, TINY_YOLO_INPUT_SIZE, TINY_YOLO_INPUT_SIZE);
                Mat mat = processor.drawBoxes(recognitions, 0.18);
                Mat ultimate = new Mat();
                Imgproc.cvtColor(mat, ultimate, Imgproc.COLOR_RGB2BGR);


                Imgcodecs.imwrite(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM) + "/yolo_v3_tiny/boxes" + i + ".jpg", ultimate);
            }
        }

    }
 
Example 19
Source File: LegofyEffect.java    From Legofy with Apache License 2.0 4 votes vote down vote up
@Override
public void initialize(Bitmap bitmap) {
    int brickSize = bitmap.getWidth() / bricksPerWidth;

    int imageWidth = bricksPerWidth;
    int imageHeight = (int) (((float) bitmap.getHeight()) / bitmap.getWidth() * bricksPerWidth);

    brickBitmap = Bitmap.createScaledBitmap(BitmapFactory.decodeResource(resources, R.drawable.brick), brickSize, brickSize, false);


    baseBitmap = Bitmap.createScaledBitmap(bitmap, imageWidth, imageHeight, true);
    legofiedBitmap = Bitmap.createBitmap(imageWidth * brickSize, imageHeight * brickSize, Bitmap.Config.ARGB_4444);
    amountOfBricks = imageWidth * imageHeight;

    canvas = new Canvas(legofiedBitmap);
    paint = new Paint();

    initializePositions();
    currentPosition = 0;

    bricksPerFrame = amountOfBricks / (duration / getFrameDuration());

}
 
Example 20
Source File: BitmapUtils.java    From MultiView with Apache License 2.0 4 votes vote down vote up
/**
 * Resize a bitmap object to fit the passed width and height
 * 
 * @param input
 *           The bitmap to be resized
 * @param destWidth
 *           Desired maximum width of the result bitmap
 * @param destHeight
 *           Desired maximum height of the result bitmap
 * @return A new resized bitmap
 * @throws OutOfMemoryError
 *            if the operation exceeds the available vm memory
 */
public static Bitmap resizeBitmap( final Bitmap input, int destWidth, int destHeight, int rotation ) throws OutOfMemoryError {

	int dstWidth = destWidth;
	int dstHeight = destHeight;
	final int srcWidth = input.getWidth();
	final int srcHeight = input.getHeight();

	if ( rotation == 90 || rotation == 270 ) {
		dstWidth = destHeight;
		dstHeight = destWidth;
	}

	boolean needsResize = false;
	float p;
	if ( ( srcWidth > dstWidth ) || ( srcHeight > dstHeight ) ) {
		needsResize = true;
		if ( ( srcWidth > srcHeight ) && ( srcWidth > dstWidth ) ) {
			p = (float) dstWidth / (float) srcWidth;
			dstHeight = (int) ( srcHeight * p );
		} else {
			p = (float) dstHeight / (float) srcHeight;
			dstWidth = (int) ( srcWidth * p );
		}
	} else {
		dstWidth = srcWidth;
		dstHeight = srcHeight;
	}

	if ( needsResize || rotation != 0 ) {
		Bitmap output;

		if ( rotation == 0 ) {
			output = Bitmap.createScaledBitmap(input, dstWidth, dstHeight, true);
		} else {
			Matrix matrix = new Matrix();
			matrix.postScale( (float) dstWidth / srcWidth, (float) dstHeight / srcHeight );
			matrix.postRotate( rotation );
			output = Bitmap.createBitmap(input, 0, 0, srcWidth, srcHeight, matrix, true);
		}
		return output;
	} else
		return input;
}