安卓调用相机拍照并返回预览及相关类型换(略缩图,画质糊)原图预览参考传送门
- 今年主要在忙新项目,安卓也有很一段时间没有写了。安卓相关的博客也没有更新,今天来简单分享一下一个小需求吧。
- 写在之后,由于此方法返回的道德bitmap是被压缩过的,预览图片会很糊,不满足需求固又尝试了一个新的办法拍照返回预览!
- 》》》安卓调用系统相机拍照并返回预览(原图预览)《《《
一、demo预览
先简单写一个demo,效果如图,点击拍照以后返回图片覆盖在指定位置。
点击拍照以后直接调用相机
拍照成功后返回显示预览
以上便是demo预览。
二、xml代码和activity简单代码描述。
布局文件代码:
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginTop="10sp"
android:orientation="vertical">
<ImageView
android:id="@+id/photoImageView"
android:layout_width="match_parent"
android:layout_height="400dp"
android:layout_marginTop="10sp"
android:layout_marginBottom="20sp"
android:layout_weight="1"
android:src="@drawable/boundary" />
<Button
android:id="@+id/takePhotoButton"
android:layout_width="200sp"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_weight="1"
android:background="@drawable/button_shape"
android:onClick="onTakePhotoButtonClicked"
android:text="拍 照"
android:textSize="23sp" />
</LinearLayout>
</android.support.constraint.ConstraintLayout>
Activity代码:
//初始化activity
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.take_photo);
photoImageView = (ImageView)findViewById(R.id.photoImageView);
}
//监听拍照按钮,点击拍照调用相机
public void onTakePhotoButtonClicked(View v){
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent, 2);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 2 && resultCode == RESULT_OK && null != data) {
Bundle bundle = data.getExtras();
//intent跳转携带参数返回,data转化成Bitmap,获得的是个略缩图
photo = (Bitmap) bundle.get("data");
//将预览图放进预览框
photoImageView.setImageBitmap(photo);
photoBytes = CommonCode.bitmapToByte(photo);
}
super.onActivityResult(requestCode, resultCode, data);
}
以上便大功告成
三、顺便写几个转换工具方法吧
Bitmap旋转角度:
public static Bitmap rotateBitmap(Bitmap origin, float alpha) {
if (origin == null) {
return null;
}
int width = origin.getWidth();
int height = origin.getHeight();
Matrix matrix = new Matrix();
matrix.setRotate(alpha);
// 围绕原地进行旋转
Bitmap newBM = Bitmap.createBitmap(origin, 0, 0, width, height, matrix, false);
if (newBM.equals(origin)) {
return newBM;
}
origin.recycle();
return newBM;
}
Bitmap转byte[]
public static byte[] bitmapToByte(Bitmap bitmap){
int bytes = bitmap.getByteCount();
ByteBuffer buf = ByteBuffer.allocate(bytes);
bitmap.copyPixelsToBuffer(buf);
return buf.array();
}
最近忙着离职、工作交接和搬家,一直没时间来写博客了,今天遇到个简单的功能,简单分享记录下这个demo吧。希望对需要的小伙伴有所帮助!2020结束了,博主这边工作也算是告一段落了。现在已经2021了,希望小伙伴们在新的一年里升职加薪,技术进步!过几天来分享下前段时间遇到的面筋吧。
- 一直(只)不务正业的Java后端