下面列出了怎么用android.graphics.Bitmap的API类实例代码及写法,或者点击链接到github查看源代码。
/**
* 等比例压缩到指定尺寸 默认到 1920 以下
*
* @param path 图片路径
*/
public static Bitmap compressByDimension(String path) {
BitmapFactory.Options options = new BitmapFactory.Options();
// 开始读入图片,此时把options.inJustDecodeBounds 设回true了
options.inJustDecodeBounds = true;
// 此时返回 bitmap 为空,并不会真正的加载图片
Bitmap bitmap = BitmapFactory.decodeFile(path, options);
options.inJustDecodeBounds = false;
int w = options.outWidth;
int h = options.outHeight;
// 缩放比,由于是固定比例缩放,只用高或者宽其中一个数据进行计算即可
int be = getZoomScale(w, h, maxDimension);
// 设置缩放比例
options.inSampleSize = be;
// 重新读入图片,注意此时已经把options.inJustDecodeBounds 设回false了
bitmap = BitmapFactory.decodeFile(path, options);
// 等比例压缩后再进行质量压缩
return bitmap;
}
Bitmap getDefaultAppDrawable(String packageName) {
Drawable drawable = null;
try {
drawable = mPackageManager.getApplicationIcon(mPackageManager.getApplicationInfo(
packageName, 0));
} catch (NameNotFoundException e) {
e.printStackTrace();
}
if (drawable == null) {
return null;
}
if (drawable instanceof BitmapDrawable) {
return generateBitmap(((BitmapDrawable) drawable).getBitmap());
}
return generateBitmap(Bitmap.createBitmap(drawable.getIntrinsicWidth(),
drawable.getIntrinsicHeight(), Bitmap.Config.ARGB_8888));
}
public void addFront(int objectHandle, String filename, Bitmap thumbnail) {
if (maxNumPictures == 0) {
if (thumbnail != null) {
thumbnail.recycle();
}
return;
}
for (Integer i : handles) {
if (i == objectHandle) {
return;
}
}
handles.add(objectHandle);
thumbnails.add(thumbnail);
filenames.add(filename);
checkListSizes();
notifyDataSetChanged();
}
Bitmap createMenuShadowBitmap() {
menuShadowRadius = (int) flyoutMenuView.menuElevation * 2;
menuShadowInset = menuShadowRadius / 2;
int size = 2 * menuShadowRadius + 1;
Bitmap shadowBitmap = Bitmap.createBitmap(size, size, Bitmap.Config.ARGB_8888);
shadowBitmap.eraseColor(0x0); // clear
Paint paint = new Paint();
paint.setAntiAlias(true);
paint.setShader(new RadialGradient(
menuShadowRadius + 1,
menuShadowRadius + 1,
menuShadowRadius,
ColorUtils.setAlphaComponent(SHADOW_COLOR, SHADOW_ALPHA),
ColorUtils.setAlphaComponent(SHADOW_COLOR, 0),
Shader.TileMode.CLAMP));
Canvas canvas = new Canvas(shadowBitmap);
canvas.drawRect(0, 0, size, size, paint);
return shadowBitmap;
}
@Override
protected Bitmap transform(@NonNull Context context, @NonNull BitmapPool pool,
@NonNull Bitmap toTransform, int outWidth, int outHeight) {
int width = toTransform.getWidth();
int height = toTransform.getHeight();
Bitmap bitmap = pool.get(width, height, Bitmap.Config.ARGB_8888);
bitmap.setHasAlpha(true);
setCanvasBitmapDensity(toTransform, bitmap);
Canvas canvas = new Canvas(bitmap);
Paint paint = new Paint();
paint.setAntiAlias(true);
paint.setShader(new BitmapShader(toTransform, Shader.TileMode.CLAMP, Shader.TileMode.CLAMP));
drawRoundRect(canvas, paint, width, height);
return bitmap;
}
/**
* Shows the work profile badge if it is needed.
*/
private void addWorkProfileBadge(RemoteViews view) {
Resources resources = mContext.getResources();
DisplayMetrics metrics = resources.getDisplayMetrics();
int size = dpToPx(WORK_PROFILE_BADGE_SIZE_DP, metrics);
int[] colors = new int[size * size];
// Create an immutable bitmap, so that it can not be reused for painting a badge into it.
Bitmap bitmap = Bitmap.createBitmap(colors, size, size, Bitmap.Config.ARGB_8888);
Drawable inputDrawable = new BitmapDrawable(resources, bitmap);
Drawable outputDrawable = ApiCompatibilityUtils.getUserBadgedDrawableForDensity(
mContext, inputDrawable, null /* badgeLocation */, metrics.densityDpi);
// The input bitmap is immutable, so the output drawable will be a different instance from
// the input drawable if the work profile badge was applied.
if (inputDrawable != outputDrawable && outputDrawable instanceof BitmapDrawable) {
view.setImageViewBitmap(
R.id.work_profile_badge, ((BitmapDrawable) outputDrawable).getBitmap());
view.setViewVisibility(R.id.work_profile_badge, View.VISIBLE);
}
}
@TargetApi(Build.VERSION_CODES.KITKAT)
static boolean canUseForInBitmap(
Bitmap candidate, BitmapFactory.Options targetOptions) {
if (candidate == null)
return false;
if (AndroidUtil.isKitKatOrLater()) {
if (targetOptions.inSampleSize == 0)
return false;
// 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());
return byteCount <= candidate.getAllocationByteCount();
}
// 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;
}
public void albumCover(Drawable newAlbumCover) {
if(this.albumCover == newAlbumCover) return;
this.albumCover = newAlbumCover;
if(albumCover instanceof BitmapDrawable && !isNeedToFillAlbumCoverMap.containsKey(albumCover.hashCode())) {
Bitmap bitmap = ((BitmapDrawable) albumCover).getBitmap();
if(bitmap != null && !bitmap.isRecycled()) {
if(lastPaletteAsyncTask != null && !lastPaletteAsyncTask.isCancelled()) {
lastPaletteAsyncTask.cancel(true);
}
lastPaletteAsyncTask = Palette.from(bitmap).generate(palette -> {
int dominantColor = palette.getDominantColor(Integer.MAX_VALUE);
if(dominantColor != Integer.MAX_VALUE) {
Color.colorToHSV(dominantColor, hsvArray);
isNeedToFillAlbumCoverMap.put(albumCover.hashCode(), hsvArray[2] > 0.65f);
postInvalidate();
}
});
}
}
postInvalidate();
}
public TileData loadTile(MapTile tile) {
String urlString = super.buildTileUrl(tile);
Log.debug("requesting tile: "+urlString);
Bitmap bmp = null;
try {
URL url = new URL(urlString);
bmp = BitmapFactory.decodeStream(url.openConnection().getInputStream());
} catch (IOException e) {
e.printStackTrace();
return null;
}
return new TileData(BitmapUtils.createBitmapFromAndroidBitmap(bmp).compressToInternal());
}
/**
* 优得到的采样率对图片进行解析
*
* @param filename
* @param reqWidth
* @return
*/
public static Bitmap decodeSampledBitmapFromFile(String filename,
int reqWidth) {
// First decode with inJustDecodeBounds=true to check dimensions
final BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeFile(filename, options);
// Calculate inSampleSize
options.inSampleSize = calculateInSampleSize(options, reqWidth);
// Decode bitmap with inSampleSize set
options.inJustDecodeBounds = false;
return BitmapFactory.decodeFile(filename, options);
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_bitmap);
mImageView1 = (ImageView) findViewById(R.id.imageView1);
mImageView2 = (ImageView) findViewById(R.id.imageView2);
mImageView3 = (ImageView) findViewById(R.id.imageView3);
mImageView4 = (ImageView) findViewById(R.id.imageView4);
Bitmap avatar1 = BitmapFactory.decodeResource(getResources(), R.drawable.headshow1);
Bitmap avatar2 = BitmapFactory.decodeResource(getResources(), R.drawable.headshow2);
Bitmap avatar3 = BitmapFactory.decodeResource(getResources(), R.drawable.headshow3);
mBmps.add(avatar1);
mBmps.add(avatar2);
mBmps.add(avatar3);
}
public RoundedDrawable(Bitmap bitmap) {
mBitmap = bitmap;
mBitmapWidth = bitmap.getWidth();
mBitmapHeight = bitmap.getHeight();
mBitmapRect.set(0, 0, mBitmapWidth, mBitmapHeight);
mBitmapPaint = new Paint();
mBitmapPaint.setStyle(Paint.Style.FILL);
mBitmapPaint.setAntiAlias(true);
mBorderPaint = new Paint();
mBorderPaint.setStyle(Paint.Style.STROKE);
mBorderPaint.setAntiAlias(true);
mBorderPaint.setColor(mBorderColor.getColorForState(getState(), DEFAULT_BORDER_COLOR));
mBorderPaint.setStrokeWidth(mBorderWidth);
}
private void captureValues(TransitionValues transitionValues) {
View view = transitionValues.view;
Rect bounds = new Rect(0, 0, view.getWidth(), view.getHeight());
if (mFadeBehavior != FADE_BEHAVIOR_REVEAL) {
bounds.offset(view.getLeft(), view.getTop());
}
transitionValues.values.put(PROPNAME_BOUNDS, bounds);
if (Transition.DBG) {
Log.d(LOG_TAG, "Captured bounds " + transitionValues.values.get(PROPNAME_BOUNDS));
}
Bitmap bitmap = Bitmap.createBitmap(view.getWidth(), view.getHeight(),
Bitmap.Config.ARGB_8888);
if (view instanceof TextureView) {
bitmap = ((TextureView) view).getBitmap();
} else {
Canvas c = new Canvas(bitmap);
view.draw(c);
}
transitionValues.values.put(PROPNAME_BITMAP, bitmap);
// TODO: I don't have resources, can't call the non-deprecated method?
BitmapDrawable drawable = new BitmapDrawable(bitmap);
// TODO: lrtb will be wrong if the view has transXY set
drawable.setBounds(bounds);
transitionValues.values.put(PROPNAME_DRAWABLE, drawable);
}
@Override
public void onPictureTaken(byte[] data, Camera camera) {
takePhotoImg.setEnabled(true);
file = FileUtil.byteArrayToFile(data,FileUtil.FileType.IMG);
releasedCamera();
if (file == null) {
//no path to picture, return
safeToTakePicture = true;
return;
}
Bitmap bitmap = BitmapFactory.decodeFile(file.getPath());
int w = bitmap.getWidth();
int retY = toolbarTop.getHeight();
int h = w;
if (retY + w > bitmap.getHeight()) {
h = bitmap.getHeight();
retY = 0;
}
Bitmap cropBitmap = Bitmap.createBitmap(bitmap, 0, retY, w, h, null, false);
File fileCrop = BitmapUtil.getInstance().bitmapSavePath(cropBitmap);
FileUtil.deleteFile(file.getPath());
PreviewPhotoActivity.startActivity(mActivity, fileCrop.getAbsolutePath());
safeToTakePicture = true;
}
private static void setImageToView(View toView, Bitmap bitmap) {
if (toView instanceof ImageView) {
final ImageView toImageView = (ImageView) toView;
toImageView.setImageBitmap(bitmap);
} else {
ViewCompat.setBackground(toView, new BitmapDrawable(toView.getResources(), bitmap));
}
}
private static InputStream getInputStream(final AwContentsClient contentClient)
throws IOException {
final PipedInputStream inputStream = new PipedInputStream();
final PipedOutputStream outputStream = new PipedOutputStream(inputStream);
// Send the request to UI thread to callback to the client, and if it provides a
// valid bitmap bounce on to the worker thread pool to compress it into the piped
// input/output stream.
ThreadUtils.runOnUiThread(new Runnable() {
@Override
public void run() {
final Bitmap defaultVideoPoster = contentClient.getDefaultVideoPoster();
if (defaultVideoPoster == null) {
closeOutputStream(outputStream);
return;
}
AsyncTask.THREAD_POOL_EXECUTOR.execute(new Runnable() {
@Override
public void run() {
try {
defaultVideoPoster.compress(Bitmap.CompressFormat.PNG, 100,
outputStream);
outputStream.flush();
} catch (IOException e) {
Log.e(TAG, null, e);
} finally {
closeOutputStream(outputStream);
}
}
});
}
});
return inputStream;
}
public void openGallery() {
if (parentFragment == null) {
return;
}
if (Build.VERSION.SDK_INT >= 23 && parentFragment != null && parentFragment.getParentActivity() != null) {
if (parentFragment.getParentActivity().checkSelfPermission(Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
parentFragment.getParentActivity().requestPermissions(new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, 4);
return;
}
}
PhotoAlbumPickerActivity fragment = new PhotoAlbumPickerActivity(true, false, false, null);
fragment.setDelegate(new PhotoAlbumPickerActivity.PhotoAlbumPickerActivityDelegate() {
@Override
public void didSelectPhotos(ArrayList<SendMessagesHelper.SendingMediaInfo> photos) {
if (!photos.isEmpty()) {
Bitmap bitmap = ImageLoader.loadBitmap(photos.get(0).path, null, 800, 800, true);
processBitmap(bitmap);
}
}
@Override
public void startPhotoSelectActivity() {
try {
Intent photoPickerIntent = new Intent(Intent.ACTION_GET_CONTENT);
photoPickerIntent.setType("image/*");
parentFragment.startActivityForResult(photoPickerIntent, 14);
} catch (Exception e) {
FileLog.e(e);
}
}
});
parentFragment.presentFragment(fragment);
}
@SuppressLint("DefaultLocale")
public void runInference() {
RectF bound = maxBound.getBound();
int x = (int) bound.left;
int y = (int) bound.top;
int width = (int) Math.ceil(bound.width());
int height = (int) Math.ceil(bound.height());
// do crop
Bitmap bmp = Bitmap.createBitmap(bitmap, x, y, width, height);
// do scaling
Bitmap bmp64 = Bitmap.createScaledBitmap(bmp, 64, 64, true);
try {
Classifications classifications = predictor.predict(factory.fromImage(bmp64));
imageView.setImageBitmap(bmp);
List<Classifications.Classification> list = classifications.topK(3);
StringBuilder sb = new StringBuilder();
for (Classifications.Classification classification : list) {
sb.append(classification.getClassName())
.append(": ")
.append(String.format("%.2f%%", 100 * classification.getProbability()))
.append("\n");
}
textView.setText(sb.toString());
} catch (TranslateException e) {
Log.e("DoodleDraw", null, e);
}
}
@NonNull
public static ImageSource cachedBitmap(@NonNull Bitmap bitmap) {
//noinspection ConstantConditions
if (bitmap == null) {
throw new NullPointerException("Bitmap must not be null");
}
return new ImageSource(bitmap, true);
}
public static Bitmap resizeBitmap(final Bitmap input, int destWidth,
int destHeight) {
final int srcWidth = input.getWidth();
final int srcHeight = input.getHeight();
boolean needsResize = false;
float p;
if ((srcWidth > destWidth) || (srcHeight > destHeight)) {
needsResize = true;
if ((srcWidth > srcHeight) && (srcWidth > destWidth)) {
p = (float) destWidth / (float) srcWidth;
destHeight = (int) (srcHeight * p);
} else {
p = (float) destHeight / (float) srcHeight;
destWidth = (int) (srcWidth * p);
}
} else {
destWidth = srcWidth;
destHeight = srcHeight;
}
if (needsResize) {
final Bitmap output = Bitmap.createScaledBitmap(input, destWidth,
destHeight, true);
return output;
} else {
return input;
}
}
/**
* 根据丢弃记录修正同尺寸元素的重用队列长度
* 如果重用比例越小, 队列长度越小
*/
private static int fixMaximumSameDimension(Bitmap bmp, int maximumSameDimension) {
final Config cfg = getConfig(bmp);
Long key = Long.valueOf(bmp.getWidth() * 0x8000 + bmp.getHeight() * 0x20 + cfg.ordinal());
ReuseStatisticInfo record = _reuseStatistic.get(key);
if (record == null || record.recycled < 5) {
return maximumSameDimension;
}
if (record.dropPercent() < 5) {
maximumSameDimension *= 1.2;
} else if (record.dropPercent() > 20) {
maximumSameDimension *= 0.8;
} else if (record.dropPercent() > 50) {
maximumSameDimension *= 0.5;
} else if (record.dropPercent() > 80) {
maximumSameDimension *= 0.2;
} else if (record.dropPercent() > 90) {
maximumSameDimension *= 0.1;
} else if (record.dropPercent() > 95) {
maximumSameDimension = 1;
}
maximumSameDimension *= (record.reusePercent() + 0.1);
if (maximumSameDimension < 1) {
maximumSameDimension = 1;
}
return maximumSameDimension;
}
private static int getPerformanceMode(Bitmap source) {
if (Build.VERSION.SDK_INT < 28) {
return FirebaseVisionFaceDetectorOptions.FAST;
}
return source.getWidth() * source.getHeight() < MAX_SIZE ? FirebaseVisionFaceDetectorOptions.ACCURATE
: FirebaseVisionFaceDetectorOptions.FAST;
}
/**
* 将bitmap的透明度换成目标bitmap的透明度
*
* @param src 作用蒙板的bitmap
* @param target 目标bitmap
* @return 添加蒙板后的bitmap
*/
public static Bitmap 蒙版(Bitmap src, Bitmap target) {
final int width = src.getWidth(), height = src.getHeight();
int[] srcPixels = new int[width * height];
final Bitmap result = Bitmap.createBitmap(src.getWidth(), src.getHeight(), Bitmap.Config.ARGB_8888);
getBitmapPixelColor(src, (x, y, a, r, g, b) -> {
int dstA, dstPixelColor;
dstPixelColor = target.getPixel(x, y);
dstA = Color.alpha(dstPixelColor);
// result.setPixel(x, y, Color.argb(dstA, r, g, b));
srcPixels[x + y * width] = Color.argb(dstA, r, g, b);
});
result.setPixels(srcPixels, 0, width, 0, 0, width, height);
return result;
}
/**
* Saves 'theBitmap' into folder 'theFolder' with the name 'theImageName'
* @param theFolder the folder path dir you want to save it to e.g "DropBox/WorkImages"
* @param theImageName the name you want to assign to the image file e.g "MeAtLunch.png"
* @param theBitmap the image you want to save as a Bitmap
* @return returns the full path(file system address) of the saved image
*/
public String putImage(String theFolder, String theImageName, Bitmap theBitmap) {
if (theFolder == null || theImageName == null || theBitmap == null)
return null;
this.DEFAULT_APP_IMAGEDATA_DIRECTORY = theFolder;
String mFullPath = setupFullPath(theImageName);
if (!mFullPath.equals("")) {
lastImagePath = mFullPath;
saveBitmap(mFullPath, theBitmap);
}
return mFullPath;
}
@Override
public Bitmap get(String key) {
Bitmap result = null;
Reference<Bitmap> reference = softMap.get(key);
if (reference != null) {
result = reference.get();
}
return result;
}
/**
* Convert drawable to bitmap.
*
* @param drawable Drawable object to be converted.
* @return converted bitmap.
*/
private Bitmap drawableToBitmap(Drawable drawable, int width) {
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);
bitmap = cropBitmap(bitmap, width);
return bitmap;
}
@Override
public void put(Bitmap bitmap) {
int size = Util.getBitmapByteSize(bitmap);
Key key = keyPool.get(size, bitmap.getConfig());
groupedMap.put(key, bitmap);
NavigableMap<Integer, Integer> sizes = getSizesForConfig(bitmap.getConfig());
Integer current = sizes.get(key.size);
sizes.put(key.size, current == null ? 1 : current + 1);
}
@Override
protected void dispatchDraw(Canvas canvas) {
final long drawingTime = getDrawingTime();
final View handle = mHandle;
final boolean isVertical = mVertical;
drawChild(canvas, handle, drawingTime);
if (mTracking || mAnimating) {
final Bitmap cache = mContent.getDrawingCache();
if (cache != null) {
if (isVertical) {
canvas.drawBitmap(cache, 0, handle.getBottom(), null);
} else {
canvas.drawBitmap(cache, handle.getRight(), 0, null);
}
} else {
canvas.save();
canvas.translate(isVertical ? 0 : handle.getLeft() - mTopOffset,
isVertical ? handle.getTop() - mTopOffset : 0);
drawChild(canvas, mContent, drawingTime);
canvas.restore();
}
} else if (mExpanded) {
drawChild(canvas, mContent, drawingTime);
} else {
Paint paint2 = new Paint();
paint2.setColor(mBackgroundColor);
paint2.setStyle(Style.FILL);
if (isVertical) {
canvas.drawRect(0, handle.getBottom(), mContent.getRight(), mContent.getBottom(), paint2);
} else {
}
}
}
/**
* Creates a new image with the picture overlaid by the badge.
* @param userPicture A bitmap to overlay on.
* @param badge A bitmap to overlay with.
* @return A bitmap with the badge overlaying the {@code userPicture}.
*/
private static Bitmap overlayChildBadgeOnUserPicture(
Bitmap userPicture, Bitmap badge, Resources resources) {
assert userPicture.getWidth() == resources.getDimensionPixelSize(R.dimen.user_picture_size);
int borderSize = resources.getDimensionPixelOffset(R.dimen.badge_border_size);
int badgeRadius = resources.getDimensionPixelOffset(R.dimen.badge_radius);
// Create a larger image to accommodate the badge which spills the original picture.
int badgedPictureWidth =
resources.getDimensionPixelOffset(R.dimen.badged_user_picture_width);
int badgedPictureHeight =
resources.getDimensionPixelOffset(R.dimen.badged_user_picture_height);
Bitmap badgedPicture = Bitmap.createBitmap(badgedPictureWidth, badgedPictureHeight,
Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(badgedPicture);
canvas.drawBitmap(userPicture, 0, 0, null);
// Cut a transparent hole through the background image.
// This will serve as a border to the badge being overlaid.
Paint paint = new Paint();
paint.setAntiAlias(true);
paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.CLEAR));
int badgeCenterX = badgedPictureWidth - badgeRadius;
int badgeCenterY = badgedPictureHeight - badgeRadius;
canvas.drawCircle(badgeCenterX, badgeCenterY, badgeRadius + borderSize, paint);
// Draw the badge
canvas.drawBitmap(badge, badgeCenterX - badgeRadius, badgeCenterY - badgeRadius, null);
return badgedPicture;
}
public void setImageBitmap (@Nullable Bitmap bitmap) {
resizedCircularImage = bitmap;
// Special case: remove image altogether
if (bitmap == null) {
super.setImageBitmap(null);
} else {
imageHeight = resizedCircularImage.getHeight();
imageWidth = resizedCircularImage.getWidth();
viewHeight = imageHeight + (bevelStrokeWidth * 2);
viewWidth = imageWidth + (bevelStrokeWidth * 2);
setBevelVisible(bevelVisible);
}
}