美文网首页安卓工作记录
[Android] 相机拍摄图片尺寸调整与app前端显示

[Android] 相机拍摄图片尺寸调整与app前端显示

作者: 闭门造折 | 来源:发表于2019-04-25 22:33 被阅读0次

调用的是本机摄像头的PictureCallback()方法,得到一个byte[]类型的拍摄结果

步骤一 :byte[]转bitmap

首先将byte[]转换为bitmap(方便进行图像变换),其中的tmpPic就是我们预存的byte[]类型拍摄结果

Bitmap bitmap = BitmapFactory.decodeByteArray(tmpPic, 0, tmpPic.length);

步骤二:采用时间戳作为存储用的文件名

// 获取当前时间
Date date = new Date(System.currentTimeMillis());
// 设定时间格式
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMdd_HHmmss", Locale.getDefault());
// 转换时间为标准格式,并添加.jpg后缀
String filePath = dir.getAbsolutePath() + "/Take_" + dateFormat.format(date) + ".jpg";
// 创建文件
File file = new File(filePath);
file.createNewFile();
// 输出logcat提示信息
Log.d(TestTag, "FilePath:" + filePath);

步骤三:Bitmap变换

3.1:Bitmap旋转

下方代码中,bitmap为原始未处理Bitmap
使用matrix进行旋转
bitmapRoute为旋转后Bitmap

// 设定旋转角度为90度(逆时针吧,我也不太确定)
Matrix matrix = new Matrix();
matrix.postRotate(90);
// 从(0,0)开始,取width,height大小的图片进行旋转
Bitmap bitmapRoute = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, true);
// 原来的Bitmap空间不要浪费,回收一下
bitmap.recycle();
Log.d(TestTag, "Route Bitmap is set :" + bitmapRoute.getWidth() + ":" + bitmapRoute.getHeight());

3.2:Bitmap切割

从指定的坐标(tmpRow,tmpCol)开始,切割widthBit,heightBit大小区域

Bitmap bitmapCut = Bitmap.createBitmap(bitmapRoute, tmpRow, tmpCol, widthBit, heightBit);
bitmapRoute.recycle();
Log.d(TestTag, "Final Bitmap is set :" + bitmapCut.getWidth() + ":" + bitmapCut.getHeight());

3.3:Bitmap缩放

缩放成指定大小,下文使用的是960*1280的大小

Bitmap bitmapScale = Bitmap.createScaledBitmap(bitmapCut, 960 , 1280, true);
bitmapCut.recycle();
Log.d(TestTag, "Scale Bitmap is set :" + bitmapScale.getWidth() + ":" + bitmapScale.getHeight());   

步骤四:Bitmap转JPG文件

这里需要用到步骤二创建的文件

BufferedOutputStream buffStream = new BufferedOutputStream(new FileOutputStream(file));
bitmapScale.compress(Bitmap.CompressFormat.JPEG, 100, buffStream);
buffStream.flush();
buffStream.close();

步骤五:前端显示

在界面上添加一个ImageView,平时设置为不显示

image = (ImageView) findViewById(R.id.image_view);
image.setVisibility(View.INVISIBLE);  

再在onActivityResult里面添加对拍照事件的回调(比方说拍完照就显示的功能)

image.setImageBitmap(bitmap);
image.setVisibility(View.VISIBLE);    

仅需设置一下setImage的值以及设置为显示,图片就显示在前端啦

步骤六:图片触碰取消显示

这个是可做可不做的优化,虽然如果你不做,你这张图就会一直显示吧
其实就是给ImageView控件添加一个简单的点击事件就行

ImageView imageRecover = (ImageView)findViewById(R.id.image_view);
imageRecover.setOnClickListener(new OnClickListener() {
    @Override
    public void onClick(View v) {
        image.setVisibility(View.INVISIBLE);
    }
});

完整代码

完整代码请移步github项目Github项目:《Matting》 By ZaoZhe6666
在app_front中是前端展示,在UseCameraActivity.java文件中的saveJpeg()函数,即为本文所提到的所有具体用例的完整版本
代码可能存在些许出入,原项目中图片显示是为了和服务器对接并显示,拍照没有再次显示处理图的步骤,但是逻辑是一样的

相关文章

网友评论

    本文标题:[Android] 相机拍摄图片尺寸调整与app前端显示

    本文链接:https://www.haomeiwen.com/subject/hzlagqtx.html