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

The following are Jave code examples for showing how to use createScaledBitmap() of the android.graphics.Bitmap class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
+ Save this method
Example 1
Project: ProgressManager   File: a.java   View Source Code Vote up 6 votes
/**
 * Sets information describing the task with this activity for presentation inside the Recents
 * System UI. When {@link ActivityManager#getRecentTasks} is called, the activities of each task
 * are traversed in order from the topmost activity to the bottommost. The traversal continues
 * for each property until a suitable value is found. For each task the taskDescription will be
 * returned in {@link android.app.ActivityManager.TaskDescription}.
 *
 * @see ActivityManager#getRecentTasks
 * @see android.app.ActivityManager.TaskDescription
 *
 * @param taskDescription The TaskDescription properties that describe the task with this activity
 */
public void setTaskDescription(ActivityManager.TaskDescription taskDescription) {
    if (mTaskDescription != taskDescription) {
        mTaskDescription.copyFrom(taskDescription);
        // Scale the icon down to something reasonable if it is provided
        if (taskDescription.getIconFilename() == null && taskDescription.getIcon() != null) {
            final int size = ActivityManager.getLauncherLargeIconSizeInner(this);
            final Bitmap icon = Bitmap.createScaledBitmap(taskDescription.getIcon(), size, size,
                    true);
            mTaskDescription.setIcon(icon);
        }
    }
    try {
        ActivityManagerNative.getDefault().setTaskDescription(mToken, mTaskDescription);
    } catch (RemoteException e) {
    }
}
 
Example 2
Project: ProgressManager   File: a.java   View Source Code Vote up 6 votes
/**
 * Sets information describing the task with this activity for presentation inside the Recents
 * System UI. When {@link ActivityManager#getRecentTasks} is called, the activities of each task
 * are traversed in order from the topmost activity to the bottommost. The traversal continues
 * for each property until a suitable value is found. For each task the taskDescription will be
 * returned in {@link android.app.ActivityManager.TaskDescription}.
 *
 * @see ActivityManager#getRecentTasks
 * @see android.app.ActivityManager.TaskDescription
 *
 * @param taskDescription The TaskDescription properties that describe the task with this activity
 */
public void setTaskDescription(ActivityManager.TaskDescription taskDescription) {
    if (mTaskDescription != taskDescription) {
        mTaskDescription.copyFrom(taskDescription);
        // Scale the icon down to something reasonable if it is provided
        if (taskDescription.getIconFilename() == null && taskDescription.getIcon() != null) {
            final int size = ActivityManager.getLauncherLargeIconSizeInner(this);
            final Bitmap icon = Bitmap.createScaledBitmap(taskDescription.getIcon(), size, size,
                    true);
            mTaskDescription.setIcon(icon);
        }
    }
    try {
        ActivityManagerNative.getDefault().setTaskDescription(mToken, mTaskDescription);
    } catch (RemoteException e) {
    }
}
 
Example 3
Project: ProgressManager   File: a.java   View Source Code Vote up 6 votes
/**
 * Sets information describing the task with this activity for presentation inside the Recents
 * System UI. When {@link ActivityManager#getRecentTasks} is called, the activities of each task
 * are traversed in order from the topmost activity to the bottommost. The traversal continues
 * for each property until a suitable value is found. For each task the taskDescription will be
 * returned in {@link android.app.ActivityManager.TaskDescription}.
 *
 * @see ActivityManager#getRecentTasks
 * @see android.app.ActivityManager.TaskDescription
 *
 * @param taskDescription The TaskDescription properties that describe the task with this activity
 */
public void setTaskDescription(ActivityManager.TaskDescription taskDescription) {
    if (mTaskDescription != taskDescription) {
        mTaskDescription.copyFrom(taskDescription);
        // Scale the icon down to something reasonable if it is provided
        if (taskDescription.getIconFilename() == null && taskDescription.getIcon() != null) {
            final int size = ActivityManager.getLauncherLargeIconSizeInner(this);
            final Bitmap icon = Bitmap.createScaledBitmap(taskDescription.getIcon(), size, size,
                    true);
            mTaskDescription.setIcon(icon);
        }
    }
    try {
        ActivityManagerNative.getDefault().setTaskDescription(mToken, mTaskDescription);
    } catch (RemoteException e) {
    }
}
 
Example 4
Project: encdroidMC   File: ThumbnailsTask.java   View Source Code Vote up 6 votes
public static Bitmap createImageThumbnail(byte[] img){
	   try 
	    {
		    final int THUMBNAIL_SIZE = 100;
		    //InputStream is=getAssets().open("apple-android-battle.jpg");
		    Bitmap imageBitmap = BitmapFactory.decodeByteArray(img, 0, img.length);//Stream(is);

		    Float width = new Float(imageBitmap.getWidth());
		    Float height = new Float(imageBitmap.getHeight());
		    Float ratio = width/height;
		    imageBitmap = Bitmap.createScaledBitmap(imageBitmap, (THUMBNAIL_SIZE ), THUMBNAIL_SIZE, true);


		    return imageBitmap;
	    }
	    catch(Exception ex) {
	    	return null;
	    }
}
 
Example 5
Project: appinventor-extensions   File: Canvas.java   View Source Code Vote up 5 votes
private int getBackgroundPixelColor(int x, int y) {
  // If the request is out of bounds, return COLOR_NONE.
  if (x < 0 || x >= bitmap.getWidth() ||
      y < 0 || y >= bitmap.getHeight()) {
    return Component.COLOR_NONE;
  }

  try {
    // First check if anything has been drawn on the bitmap
    // (such as by DrawPoint, DrawCircle, etc.).
    int color = bitmap.getPixel(x, y);
    if (color != Color.TRANSPARENT) {
      return color;
    }

    // If nothing has been drawn on the bitmap at that location,
    // check if there is a background image.
    if (backgroundDrawable != null) {
      if (scaledBackgroundBitmap == null) {
        scaledBackgroundBitmap = Bitmap.createScaledBitmap(
            backgroundDrawable.getBitmap(),
            bitmap.getWidth(), bitmap.getHeight(),
            false);  // false argument indicates not to filter
      }
      color = scaledBackgroundBitmap.getPixel(x, y);
      return color;
    }

    // If there is no background image, use the background color.
    if (Color.alpha(backgroundColor) != 0) {
      return backgroundColor;
    }
    return Component.COLOR_NONE;
  } catch (IllegalArgumentException e) {
    // This should never occur, since we have checked bounds.
    Log.e(LOG_TAG,
        String.format("Returning COLOR_NONE (exception) from getBackgroundPixelColor."));
    return Component.COLOR_NONE;
  }
}
 
Example 6
Project: BlogBookApp   File: HmImageView.java   View Source Code Vote up 5 votes
private Bitmap applyFillType(Bitmap bitmap) {
    Log.d(TAG, "Reached applyFillType");

    float bitmapWidth = bitmap.getWidth();
    float bitmapHeight = bitmap.getHeight();
    float bitmapRatio = bitmapWidth / bitmapHeight;

    Log.d(TAG, "Bitmap Specs, Width --> " + bitmapWidth + "  Height --> " + bitmapHeight + "  Ratio --> " + bitmapRatio);

    int viewWidth = getMeasuredWidth() - getPaddingLeft() - getPaddingRight();
    int viewHeight = getMeasuredHeight() - getPaddingTop() - getPaddingBottom();

    Log.d(TAG, "ImageView Specs, Width --> " + viewWidth + "  Height --> " + viewHeight);

    if (viewWidth > 0 && viewHeight > 0) {
        switch (mFillType) {
            case FillType.WIDTH:
                Log.d(TAG, "Reached full width");
                return Bitmap.createScaledBitmap(bitmap, viewWidth, (int) (viewWidth / bitmapRatio), true);
            case FillType.HEIGHT:
                Log.d(TAG, "Reached full height -- > " + getHeight());
                return Bitmap.createScaledBitmap(bitmap, (int) (viewHeight * bitmapRatio), viewHeight, true);
        }
    }

    Log.d(TAG, "Both width and height should be greater than zero");
    return bitmap;
}
 
Example 7
Project: ChatExchange-old   File: MainActivityUtils.java   View Source Code Vote up 5 votes
@Nullable
private Drawable getIcon(String html, String chatUrl)
{
    try
    {
        Document document = Jsoup.parse(html);
        Element head = document.head();
        Element link = head.select("link").first();

        String fav = link.attr("href");
        if (!fav.contains("http"))
        {
            fav = "https:".concat(fav);
        }
        URL url = new URL(fav);

        Bitmap bmp = BitmapFactory.decodeStream(url.openConnection().getInputStream());

        String FILENAME = "FAVICON_" + chatUrl.replace("/", "");
        FileOutputStream fos = mainActivity.openFileOutput(FILENAME, Context.MODE_PRIVATE);
        bmp.compress(Bitmap.CompressFormat.PNG, 100, fos);
        fos.close();

        Resources r = mainActivity.getResources();
        int px = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 50, r.getDisplayMetrics());

        return new BitmapDrawable(Resources.getSystem(), Bitmap.createScaledBitmap(bmp, px, px, true));

    }
    catch (Exception e)
    {
        e.printStackTrace();
        return null;
    }
}
 
Example 8
Project: Ae4Team   File: AddProductActivity.java   View Source Code Vote up 5 votes
private void imageUpload(final String documentReference) {
    Log.i(TAG, "imageupload");


    StorageReference mountainsRef = storageRef.child("post").child(documentReference).child("photo.jpg");
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    Log.i(TAG, baos.toString());
    bitmap = Bitmap.createScaledBitmap(bitmap, bitmap.getWidth() / 6, bitmap.getHeight() / 6, true);
    bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
    byte[] data = baos.toByteArray();

    UploadTask uploadTask = mountainsRef.putBytes(data);
    uploadTask.addOnFailureListener(new OnFailureListener() {
        @Override
        public void onFailure(@NonNull Exception exception) {
            // Handle unsuccessful uploads
            dialog.dismiss();
            postColRef.document(documentReference).delete();
        }
    }).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
        @Override
        public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
            // taskSnapshot.getMetadata() contains file metadata such as size, content-type, and download URL.
            Uri downloadUrl = taskSnapshot.getDownloadUrl();
            dialog.dismiss();
            Toast.makeText(AddProductActivity.this, "업로드 되었습니다", Toast.LENGTH_SHORT).show();
            finish();
            Log.d(TAG, String.valueOf(downloadUrl));
        }
    });
}
 
Example 9
Project: GestureLockView   File: BitmapUtil.java   View Source Code Vote up 5 votes
/**
 * 创建缩放后的圆形位图
 *
 * @param context 上下文环境
 * @param radius  点半径
 * @param imageId 图片资源ID
 */
@Nullable
public static Bitmap createScaledCircleBitmap(Context context, int radius, int imageId) {
    // 1.获取原始图片
    Bitmap bitmap = BitmapFactory.decodeResource(context.getResources(), imageId);
    // 2.判断是否能获取到图片
    if (bitmap == null) {
        return null;
    }
    // 2.缩放至指定大小
    bitmap = Bitmap.createScaledBitmap(bitmap, radius * 2, radius * 2, false);
    // 3.创建圆形图片并返回
    return createCircleImage(bitmap);
}
 
Example 10
Project: FlickLauncher   File: BlurWallpaperProvider.java   View Source Code Vote up 5 votes
public Bitmap blur(Bitmap image) {
    int width = Math.round(image.getWidth() / mDownsampleFactor);
    int height = Math.round(image.getHeight() / mDownsampleFactor);

    Bitmap inputBitmap = Bitmap.createScaledBitmap(image, width, height, false);
    Bitmap outputBitmap = Bitmap.createBitmap(inputBitmap);

    RenderScript rs = RenderScript.create(mContext);
    ScriptIntrinsicBlur theIntrinsic = ScriptIntrinsicBlur.create(rs, Element.U8_4(rs));
    Allocation tmpIn = Allocation.createFromBitmap(rs, inputBitmap);
    Allocation tmpOut = Allocation.createFromBitmap(rs, outputBitmap);
    theIntrinsic.setRadius(mBlurRadius);
    theIntrinsic.setInput(tmpIn);
    theIntrinsic.forEach(tmpOut);
    tmpOut.copyTo(outputBitmap);

    // Have to scale it back to full resolution because antialiasing is too expensive to be done each frame
    Bitmap bitmap = Bitmap.createBitmap(image.getWidth(), image.getHeight(), Bitmap.Config.ARGB_8888);

    Canvas canvas = new Canvas(bitmap);
    canvas.save();
    canvas.scale(mDownsampleFactor, mDownsampleFactor);
    canvas.drawBitmap(outputBitmap, 0, 0, mPaint);
    canvas.restore();

    return bitmap;
}
 
Example 11
Project: cafebar   File: CafeBarUtil.java   View Source Code Vote up 5 votes
@Nullable
private static Drawable getResizedDrawable(@NonNull Context context, @Nullable Drawable drawable,
                                           int color, boolean tint) {
    try {
        if (drawable == null) {
            LogUtil.d("drawable: null");
            return null;
        }

        if (tint) {
            drawable.setColorFilter(color, PorterDuff.Mode.SRC_IN);
            drawable.mutate();
        }

        int size = context.getResources().getDimensionPixelSize(R.dimen.cafebar_icon_size);
        Bitmap bitmap = Bitmap.createBitmap(drawable.getIntrinsicWidth(),
                drawable.getIntrinsicHeight(), Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(bitmap);
        drawable.setBounds(0, 0, canvas.getWidth(), canvas.getHeight());
        drawable.draw(canvas);

        return new BitmapDrawable(context.getResources(),
                Bitmap.createScaledBitmap(bitmap, size, size, true));
    } catch (Exception | OutOfMemoryError e) {
        LogUtil.e(Log.getStackTraceString(e));
        return null;
    }
}
 
Example 12
Project: GeekZone   File: ImageUtils.java   View Source Code Vote up 5 votes
public static Bitmap compressBitmap(byte[] data, int maxWidth, int maxHeight) {

        BitmapFactory.Options decodeOptions = new BitmapFactory.Options();
        Bitmap bitmap = null;
        // 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(maxWidth, maxHeight, actualWidth, actualHeight);
        int desiredHeight = getResizedDimension(maxHeight, maxWidth, actualHeight, actualWidth);

        // TODO(ficus): Do we need this or is it okay since API 8 doesn't
        // Decode to the nearest power of two scaling factor.
        decodeOptions.inJustDecodeBounds = false;
        // support it?
        // decodeOptions.inPreferQualityOverSpeed = PREFER_QUALITY_OVER_SPEED;
        decodeOptions.inSampleSize = findBestSampleSize(actualWidth, actualHeight, desiredWidth, desiredHeight);
        Log.i(TAG, "compressBitmap: inSampleSize=" + decodeOptions.inSampleSize);
        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;
        }

        return bitmap;
    }
 
Example 13
Project: wg_planer   File: ProfileSettingsActivity.java   View Source Code Vote up 5 votes
private Bitmap scaleBitmap(Bitmap bitmap) {
    int maxLength = Math.max(bitmap.getHeight(), bitmap.getWidth());
    float scale = (float) 800 / (float) maxLength;

    int newWidth = Math.round(bitmap.getWidth() * scale);
    int newHeight = Math.round(bitmap.getHeight() * scale);

    return Bitmap.createScaledBitmap(bitmap, newWidth, newHeight, true);
}
 
Example 14
Project: Cluttr   File: BitmapUtils.java   View Source Code Vote up 5 votes
/**
 * Resize the given bitmap to the given width/height by the given option.<br>
 */
static Bitmap resizeBitmap(Bitmap bitmap, int reqWidth, int reqHeight, CropImageView.RequestSizeOptions options) {
    try {
        if (reqWidth > 0 && reqHeight > 0 && (options == CropImageView.RequestSizeOptions.RESIZE_FIT ||
                options == CropImageView.RequestSizeOptions.RESIZE_INSIDE ||
                options == CropImageView.RequestSizeOptions.RESIZE_EXACT)) {

            Bitmap resized = null;
            if (options == CropImageView.RequestSizeOptions.RESIZE_EXACT) {
                resized = Bitmap.createScaledBitmap(bitmap, reqWidth, reqHeight, false);
            } else {
                int width = bitmap.getWidth();
                int height = bitmap.getHeight();
                float scale = Math.max(width / (float) reqWidth, height / (float) reqHeight);
                if (scale > 1 || options == CropImageView.RequestSizeOptions.RESIZE_FIT) {
                    resized = Bitmap.createScaledBitmap(bitmap, (int) (width / scale), (int) (height / scale), false);
                }
            }
            if (resized != null) {
                if (resized != bitmap) {
                    bitmap.recycle();
                }
                return resized;
            }
        }
    } catch (Exception e) {
        Log.w("AIC", "Failed to resize cropped image, return bitmap before resize", e);
    }
    return bitmap;
}
 
Example 15
Project: HabitUp   File: UserAccount.java   View Source Code Vote up 5 votes
/**
     * Helper method - tries to resize the image by a scaling factor.
     * @param img Bitmap
     * @return Bitmap after resizing
     */
    private Bitmap resizeImage(Bitmap img) {
//        ByteArrayOutputStream stream = new ByteArrayOutputStream();
//        img.compress(Bitmap.CompressFormat.JPEG, 70, stream);
//        byte[] imgData = stream.toByteArray();
//        return BitmapFactory.decodeByteArray(imgData, 0, imgData.length);
        double scaleFactor = 0.95;
        return Bitmap.createScaledBitmap(img, (int) (img.getWidth() * scaleFactor), (int) (img.getHeight() * scaleFactor), true);
    }
 
Example 16
Project: anyRTC-RTCP-Android   File: QRCode.java   View Source Code Vote up 5 votes
/**
 * 比方法2的颜色黑一些
 *
 * @param text
 * @param size
 * @param mBitmap
 * @return
 */
public static Bitmap createQRCodeWithLogo4(String text, int size, Bitmap mBitmap) {
    try {
        IMAGE_HALFWIDTH = size / 10;
        Hashtable<EncodeHintType, Object> hints = new Hashtable<>();
        hints.put(EncodeHintType.CHARACTER_SET, "utf-8");

        hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);
        BitMatrix bitMatrix = new QRCodeWriter().encode(text,
                BarcodeFormat.QR_CODE, size, size, hints);

        //将logo图片按martix设置的信息缩放
        mBitmap = Bitmap.createScaledBitmap(mBitmap, size, size, false);

        int[] pixels = new int[size * size];
        boolean flag = true;
        for (int y = 0; y < size; y++) {
            for (int x = 0; x < size; x++) {
                if (bitMatrix.get(x, y)) {
                    if (flag) {
                        flag = false;
                        pixels[y * size + x] = 0xff000000;
                    } else {
                        pixels[y * size + x] = mBitmap.getPixel(x, y);
                        flag = true;
                    }
                } else {
                    pixels[y * size + x] = 0xffffffff;
                }
            }
        }
        Bitmap bitmap = Bitmap.createBitmap(size, size,
                Bitmap.Config.ARGB_8888);
        bitmap.setPixels(pixels, 0, size, 0, 0, size, size);
        return bitmap;
    } catch (WriterException e) {
        e.printStackTrace();
        return null;
    }
}
 
Example 17
Project: android-titanium-imagecropper   File: BitmapUtils.java   View Source Code Vote up 5 votes
/** Resize the given bitmap to the given width/height by the given option.<br> */
static Bitmap resizeBitmap(
    Bitmap bitmap, int reqWidth, int reqHeight, CropImageView.RequestSizeOptions options) {
  try {
    if (reqWidth > 0
        && reqHeight > 0
        && (options == CropImageView.RequestSizeOptions.RESIZE_FIT
            || options == CropImageView.RequestSizeOptions.RESIZE_INSIDE
            || options == CropImageView.RequestSizeOptions.RESIZE_EXACT)) {

      Bitmap resized = null;
      if (options == CropImageView.RequestSizeOptions.RESIZE_EXACT) {
        resized = Bitmap.createScaledBitmap(bitmap, reqWidth, reqHeight, false);
      } else {
        int width = bitmap.getWidth();
        int height = bitmap.getHeight();
        float scale = Math.max(width / (float) reqWidth, height / (float) reqHeight);
        if (scale > 1 || options == CropImageView.RequestSizeOptions.RESIZE_FIT) {
          resized =
              Bitmap.createScaledBitmap(
                  bitmap, (int) (width / scale), (int) (height / scale), false);
        }
      }
      if (resized != null) {
        if (resized != bitmap) {
          bitmap.recycle();
        }
        return resized;
      }
    }
  } catch (Exception e) {
    Log.w("AIC", "Failed to resize cropped image, return bitmap before resize", e);
  }
  return bitmap;
}
 
Example 18
Project: AndroidSDK2.0   File: SampleView.java   View Source Code Vote up 4 votes
public void setPage( float width, float height,float dx, float dy ,String backImagePath)
	{
		if ( getWidth() <= 0 || getHeight() <= 0 || width <= 0 || height <= 0 )
		{
			return;
		}
		paper_offsetX = dx;
		paper_offsetY = dy;
		paper_width = width;
		paper_height = height;

		float width_ratio = getWidth() / paper_width;
		float height_ratio = getHeight() / paper_height;

		if(mZoomFitType == ZoomFitType.FIT_SCREEN)
			paper_scale = Math.min( width_ratio, height_ratio );
		else if(mZoomFitType == ZoomFitType.FIT_WIDTH)
			paper_scale = width_ratio;
		else
			paper_scale = height_ratio;

//		paper_scale = Math.max( width_ratio, height_ratio );

		int docWidth = (int) (paper_width * paper_scale);
		int docHeight = (int) (paper_height * paper_scale);

		int mw = getWidth() - docWidth;
		int mh = getHeight() - docHeight;

		if(mZoomFitType == ZoomFitType.FIT_SCREEN)
		{
			offsetX = mw / 2;
			offsetY = mh / 2;
		}
		else
		{
			offsetX = 0;
			offsetY = 0;

		}

		Bitmap temp_pdf3 = BitmapFactory.decodeFile( backImagePath );
		background = Bitmap.createScaledBitmap( temp_pdf3, docWidth, docHeight, true );

	}
 
Example 19
Project: Viajes   File: BitmapScaler.java   View Source Code Vote up 4 votes
public static Bitmap scaleToFitHeight(Bitmap b, int height)
{
	float factor = height / (float) b.getHeight();
	return Bitmap.createScaledBitmap(b, (int) (b.getWidth() * factor), height, true);
}
 
Example 20
Project: AndroidUtilCode-master   File: ImageUtils.java   View Source Code Vote up 3 votes
/**
 * 缩放图片
 *
 * @param src       源图片
 * @param newWidth  新宽度
 * @param newHeight 新高度
 * @param recycle   是否回收
 * @return 缩放后的图片
 */
public static Bitmap scale(Bitmap src, int newWidth, int newHeight, boolean recycle) {
    if (isEmptyBitmap(src)) return null;
    Bitmap ret = Bitmap.createScaledBitmap(src, newWidth, newHeight, true);
    if (recycle && !src.isRecycled()) src.recycle();
    return ret;
}