当前位置: 代码迷 >> 综合 >> Bitmap createBitmap()裁剪图片
  详细解决方案

Bitmap createBitmap()裁剪图片

热度:73   发布时间:2023-12-13 06:16:14.0

最近实验中用到了预览帧的处理,但是我们在配合采集时只需要中间一部分的图案的信息。因此便用到了Bitmap的裁剪。也就用到了 createBitmap() 这个方法。这里仅做一下记录。

这是官方的API介绍

 /*** Returns an immutable bitmap from the specified subset of the source* bitmap. The new bitmap may be the same object as source, or a copy may* have been made. It is initialized with the same density and color space* as the original bitmap.** @param source The bitmap we are subsetting* @param x The x coordinate of the first pixel in source* @param y The y coordinate of the first pixel in source* @param width The number of pixels in each row* @param height The number of rows* @return A copy of a subset of the source bitmap or the source bitmap itself.* @throws IllegalArgumentException if the x, y, width, height values are* outside of the dimensions of the source bitmap, or width is <= 0,* or height is <= 0*/public static Bitmap createBitmap(@NonNull Bitmap source, int x, int y, int width, int height) {
    return createBitmap(source, x, y, width, height, null, false);}
  • @param source 需要裁剪的bitmap
  • @param x 裁剪x点起始坐标(横向)
  • @param y 裁剪y点起始坐标(纵向)
  • @param width 裁剪后,新生成的bitmap的宽度
  • @param height 裁剪后,新生成的bitmap的高度
  • @return 返回一个裁剪过的bitmap 或者为操作过的(原)bitmap

这里需要注意的一个点是裁剪图片的大小不能超过原图
x+wight <= source.getWidth();以及y+height <= source.getHeight();

if (x + width > source.getWidth()) {
    throw new IllegalArgumentException("x + width must be <= bitmap.width()");}
if (y + height > source.getHeight()) {
    throw new IllegalArgumentException("y + height must be <= bitmap.height()");}

只是写了简单的展示裁剪后的图片

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.ImageView;public class MainActivity extends AppCompatActivity {
    private ImageView imageView;@Overrideprotected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);imageView = (ImageView)findViewById(R.id.appIcon);//使用Bitmap获取保存在drawable中的图片Bitmap bitmap = BitmapFactory.decodeResource(getResources(),R.drawable.head);int width = bitmap.getWidth();int height = bitmap.getHeight();System.out.println("Bitmap weight = "+width+" Bitmap height "+height);Bitmap bitmap1 = Bitmap.createBitmap(bitmap, width/3, height/4, bitmap.getWidth() /3, bitmap.getHeight() /2);imageView.setImageBitmap(bitmap1);}
}
  相关解决方案