Bitmap常用方法

普通方法

  • public boolean compress (Bitmap.CompressFormat format, int quality, OutputStream stream)将位图的压缩到指定的OutputStream,可以理解成将Bitmap保存到文件中!format:格式,PNG,JPG等;quality:压缩质量,0-100,0表示最低画质压缩,100最大质量(PNG无损,会忽略品质设定)stream:输出流返回值代表是否成功压缩到指定流!
  • void recycle():回收位图占用的内存空间,把位图标记为Dead
  • boolean isRecycled():判断位图内存是否已释放
  • int getWidth():获取位图的宽度
  • int getHeight():获取位图的高度
  • boolean isMutable():图片是否可修改
  • int getScaledWidth(Canvas canvas):获取指定密度转换后的图像的宽度
  • int getScaledHeight(Canvas canvas):获取指定密度转换后的图像的高度

静态方法

  • Bitmap createBitmap(Bitmap src):以src为原图生成不可变得新图像
  • Bitmap createScaledBitmap(Bitmap src, int dstWidth,int dstHeight, boolean filter):以src为原图,创建新的图像,指定新图像的高宽以及是否变。
  • Bitmap createBitmap(int width, int height, Config config):创建指定格式、大小的位图
  • Bitmap createBitmap(Bitmap source, int x, int y, int width, intheight)以source为原图,创建新的图片,指定起始坐标以及新图像的高宽。
  • public static Bitmap createBitmap(Bitmap source, int x, int y, int width, int height,Matrix m, boolean filter)

BitmapFactory.Option可设置参数:

  • boolean inJustDecodeBounds——如果设置为true,不获取图片,不分配内存,但会返回图片的高宽度信息。
  • int inSampleSize——图片缩放的倍数。如果设为4,则宽和高都为原来的1/4,则图是原来的1/16。
  • int outWidth——获取图片的宽度值
  • int outHeight——获取图片的高度值
  • int inDensity——用于位图的像素压缩比
  • int inTargetDensity——用于目标位图的像素压缩比(要生成的位图)
  • boolean inScaled——设置为true时进行图片压缩,从inDensity到inTargetDensity。

好吧,就贴这么多吧,要用自己查文档~


获取Bitmap位图

贴一个获取Bitmap工具类:

package com.deepreality.bitmapdemo;import android.content.Context;import android.content.res.Resources;import android.graphics.Bitmap;import android.graphics.BitmapFactory;import android.graphics.drawable.BitmapDrawable;import java.io.IOException;import java.io.InputStream;/** * 获取Bitmap的工具类 */public class BitmapUtils {    /**     * 通过BitmapDrawable来获取Bitmap     * @param mContext     * @param fileName     * @return     */    public static Bitmap getBitmapFromBitmapDrawable(Context mContext, String fileName) {        BitmapDrawable bmpMeizi = null;        try {            bmpMeizi = new BitmapDrawable(mContext.getAssets().open(fileName));//"pic_meizi.jpg"            Bitmap mBitmap = bmpMeizi.getBitmap();            return mBitmap;        } catch (IOException e) {            e.printStackTrace();        }        return null;    }    /**     * 通过资源ID获取Bitmap     * @param res     * @param resId     * @return     */    public static Bitmap getBitmapFromResource(Resources res, int resId) {        return BitmapFactory.decodeResource(res, resId);    }    /**     * 通过文件路径来获取Bitmap     * @param pathName     * @return     */    public static Bitmap getBitmapFromFile(String pathName) {        return BitmapFactory.decodeFile(pathName);    }    /**     * 通过字节数组来获取Bitmap     * @param b     * @return     */    public static Bitmap Bytes2Bimap(byte[] b) {        if (b.length != 0) {            return BitmapFactory.decodeByteArray(b, 0, b.length);        } else {            return null;        }    }    /**     * 通过输入流InputStream来获取Bitmap     * @param inputStream     * @return     */    public static Bitmap getBitmapFromStream(InputStream inputStream) {        return BitmapFactory.decodeStream(inputStream);    }}

实例如下:

1.图片剪切;2.图片缩放;3.截屏功能。

效果如下:

主要代码如下:

package com.deepreality.bitmapdemo;import android.Manifest;import android.content.pm.PackageManager;import android.graphics.Bitmap;import android.graphics.Canvas;import android.os.Build;import android.support.v4.app.ActivityCompat;import android.support.v4.content.ContextCompat;import android.support.v7.app.AppCompatActivity;import android.os.Bundle;import android.util.Log;import android.view.View;import android.widget.Button;import android.widget.ImageView;import android.widget.Toast;import java.io.ByteArrayOutputStream;import java.io.FileNotFoundException;import java.io.FileOutputStream;import java.io.IOException;import javax.security.auth.login.LoginException;public class MainActivity extends AppCompatActivity implements View.OnClickListener {    private ImageView ivBitmap, ivClipBitmap, ivZoomBitmap;    private Button btnClip;    private Bitmap bitmap = null;    static ByteArrayOutputStream byteOut = null;    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);        //判断android版本号,弹出申请权限        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {            showConfirmAppPermissions();        }        bindViews();    }    private void bindViews() {        ivBitmap = findViewById(R.id.main_img);        ivClipBitmap = findViewById(R.id.main_imgClipBitmap);        ivZoomBitmap = findViewById(R.id.main_imgZoomBitmap);        btnClip = findViewById(R.id.main_btnClip);        btnClip.setOnClickListener(this);        Bitmap bitmap = BitmapUtils.getBitmapFromResource(getResources(), R.mipmap.meizi);        ivBitmap.setImageBitmap(bitmap);        //bitmap进行裁剪,基于x,y坐标        Bitmap bitmapClipBitmap = Bitmap.createBitmap(bitmap,100, 100, 500, 500);        ivClipBitmap.setImageBitmap(bitmapClipBitmap);        //bitmap进行缩放        Bitmap bitmapZoomBitmap = Bitmap.createScaledBitmap(bitmap, 500, 500, true);        ivZoomBitmap.setImageBitmap(bitmapZoomBitmap);    }    /**     * 屏幕截图     */    private void captureScreen() {        Runnable runnable = new Runnable() {            @Override            public void run() {                try{                    //获取顶级视图                    final View contentView = getWindow().getDecorView();                    Log.e("HEHE",contentView.getHeight()+":"+contentView.getWidth());                    //创建指定格式、大小的位图                    bitmap = Bitmap.createBitmap(contentView.getWidth(),                            contentView.getHeight(), Bitmap.Config.ARGB_4444);                    //绘制视图                    contentView.draw(new Canvas(bitmap));                    ByteArrayOutputStream byteOut = new ByteArrayOutputStream();                    bitmap.compress(Bitmap.CompressFormat.JPEG, 100, byteOut);                    //图片保存                    savePic(bitmap, "/mnt/sdcard/Pictures/short.png");                }catch (Exception e){e.printStackTrace();}                finally {                    try{                        if (null != byteOut)                            byteOut.close();                        if (null != bitmap && !bitmap.isRecycled()) {                            bitmap.recycle();                            //bitmap = null;                        }                    }catch (IOException e){e.printStackTrace();}                }            }        };        try {            runnable.run();        } catch (Exception e) {            e.printStackTrace();        }    }    /**     * 截图图片保存     * @param b     * @param strFileName     */    private void savePic(Bitmap b, String strFileName) {        FileOutputStream fos = null;        try {            fos = new FileOutputStream(strFileName);            if (null != fos) {                boolean success= b.compress(Bitmap.CompressFormat.PNG, 100, fos);                fos.flush();                fos.close();                if (success) {                    Log.e("result", "截屏成功!");                    Toast.makeText(MainActivity.this, "截屏成功", Toast.LENGTH_SHORT).show();                }            }        } catch (FileNotFoundException e) {            e.printStackTrace();        } catch (IOException e) {            e.printStackTrace();        }    }    @Override    public void onClick(View v) {        switch (v.getId()) {            case R.id.main_btnClip: {                captureScreen();                break;            }            default:break;        }    }    // 7.0动态申请权限    public void showConfirmAppPermissions() {        if (ContextCompat.checkSelfPermission(this,                Manifest.permission.WRITE_EXTERNAL_STORAGE) !=                PackageManager.PERMISSION_GRANTED) {            if (ActivityCompat.shouldShowRequestPermissionRationale(this,                    Manifest.permission.WRITE_EXTERNAL_STORAGE)) {            } else {                ActivityCompat.requestPermissions(this,                        new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE,                                Manifest.permission.READ_EXTERNAL_STORAGE}, 1);            }        }    }}

更多相关文章

  1. Android(安卓)ScaleType 详解,使用
  2. Android通过OMA获得ESE的CPLC
  3. android获取Mac地址和IP 地址
  4. Android——拍照、剪切、得到图片/从相册中选择照片(api19以上和
  5. android N 获取手机内存信息方案
  6. android头像设置:从本地照片库或拍照获取并剪裁
  7. Android(安卓)仿百度网页音乐播放器圆形图片转圈播放效果
  8. TextView获取父控件的绘图状态
  9. Android进阶---Android(安卓)Webview重定向问题解决

随机推荐

  1. jQuery 三级联动选项栏
  2. 深入学习jQuery选择器系列第七篇——表单
  3. 没有定义ReferenceError jquery - 仅限f
  4. jQuery中的.bind()、.live()和.delegate(
  5. 使用jQuery解析JSON数据
  6. DataTables警告:table id = DataTables_Ta
  7. 在html表的第一行后追加行
  8. Jquery隐藏()除一个类外所有具有特定类的
  9. 从一个页面上的AJAX帖子获得NTLM挑战
  10. 如何设置请求标头字符串[重复]