android将照片压缩并显示,android拍照选择图库后将照片剪裁压缩显示到imageview上 -电脑资料...

调用图库和拍照的时候权限:

java 代码:

public class KujieSY extends Activity implements OnClickListener{

/** (非 Javadoc)

* 方法名: onCreate

* 描述:

* 作者 vencent

* @param savedInstanceState

* @see android.app.Activity#onCreate(android.os.Bundle)

*/

private TextView backs;

private ImageView images;

String takephoto="";

File PicFile;

KujieSY self=KujieSY.this;

@Override

protected void onCreate(Bundle savedInstanceState) {

// TODO Auto-generated method stub

super.onCreate(savedInstanceState);

setContentView(R.layout.kuaijieshouyin);

initView();

}

public void initView(){

backs=(TextView)findViewById(R.id.backs);

images=(ImageView)findViewById(R.id.images);

backs.setOnClickListener(this);

images.setOnClickListener(this);

}

/** (非 Javadoc)

* 方法名: onClick

* 描述:

* 作者 vencent

* @param arg0

* @see android.view.View.OnClickListener#onClick(android.view.View)

*/

@Override

public void onClick(View v) {

// TODO Auto-generated method stub

switch (v.getId()) {

case R.id.backs:

finish();

break;

case R.id.images:

new AlertDialog.Builder(this)

.setTitle("选择传图方式")

.setIcon(R.drawable.logoyy)

.setPositiveButton("图库选择",

new DialogInterface.OnClickListener() {

@Override

public void onClick(DialogInterface arg0,

int arg1) {

Intent intent = new Intent(Intent.ACTION_PICK, null);

intent.setDataAndType(

MediaStore.Images.Media.EXTERNAL_CONTENT_URI,

"image/*");

startActivityForResult(intent, 1);

}

}).setNegativeButton("拍照", new DialogInterface.OnClickListener() {

@Override

public void onClick(DialogInterface arg0, int arg1) {

// TODO Auto-generated method stub

takephoto=savepic();

Intent imageCaptureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);

imageCaptureIntent.putExtra(MediaStore.EXTRA_OUTPUT,

Uri.fromFile(PicFile));

imageCaptureIntent.putExtra("android.intent.extra.videoQuality", 0);

startActivityForResult(imageCaptureIntent, 2);

}

}).show();

break;

}

}

public String savepic(){

File files=new File(IMP.saveimages);

if(!files.exists()){

files.mkdirs();

}

String picpath=IMP.saveimages+"/"+System.currentTimeMillis()+".jpg";

PicFile=new File(picpath);

return picpath;

}

/** (非 Javadoc)

* 方法名: onActivityResult

* 描述:

* 作者 vencent

* @param requestCode

* @param resultCode

* @param data

* @see android.app.Activity#onActivityResult(int, int, android.content.Intent)

*/

@Override

protected void onActivityResult(int requestCode, int resultCode, Intent data) {

// TODO Auto-generated method stub

super.onActivityResult(requestCode, resultCode, data);

if(resultCode==0){

return;

}

switch (requestCode) {

case 1:

Uri selectedImage = data.getData();

String[] filePathColumn = { MediaStore.Images.Media.DATA };

Cursor cursor = getContentResolver().query(selectedImage,

filePathColumn, null, null, null);

cursor.moveToFirst();

int columnIndex = cursor.getColumnIndex(filePathColumn[0]);

String picturePath = cursor.getString(columnIndex);

//Bitmap bitmap=getLoacalBitmap(data.getDataString());

String newfileselect=IMP.saveimages+"/"+System.currentTimeMillis()+".jpg";

ImageCrop.Crop(self, picturePath, newfileselect);

images.setImageBitmap(BitmapFactory.decodeFile(newfileselect));

break;

case 2:

String newfile=IMP.saveimages+"/"+System.currentTimeMillis()+".jpg";

ImageCrop.Crop(self, PicFile.getAbsolutePath(), newfile);

images.setImageBitmap(BitmapFactory.decodeFile(newfile));

break;

}

}

/**

*

* @方法名: startPhotoZoom

* @描述: TODO(裁剪照片)

* @作者 张丽平

* @参数 @param uri

* @返回值 void

* @throws

*/

public void startPhotoZoom(Uri uri){

Intent intent = new Intent("com.android.camera.action.CROP");

intent.setDataAndType(uri, "image/*");

intent.putExtra("crop", "true");

// aspectX aspectY 是宽高的比例

intent.putExtra("aspectX", 1);

intent.putExtra("aspectY", 1);

// // outputX outputY 是裁剪图片宽高

intent.putExtra("outputX", 128);

intent.putExtra("outputY", 128);

intent.putExtra("return-data", true);

startActivityForResult(intent, 3);

}

}

压缩图片:

package com.jfy.app;

import java.io.BufferedInputStream;

import java.io.Closeable;

import java.io.File;

import java.io.IOException;

import java.io.InputStream;

import java.io.OutputStream;

import java.net.URISyntaxException;

import org.apache.http.conn.ClientConnectionManager;

import android.content.ContentResolver;

import android.content.Context;

import android.graphics.Bitmap;

import android.graphics.BitmapFactory;

import android.media.ThumbnailUtils;

import android.net.Uri;

public class ImageCrop {

public static boolean Crop(Context context, String pathName,

String newPathName) {

return Crop(context, pathName, newPathName, 1024);

}

public static boolean Crop(Context context, String pathName,

String newPathName, int maxXY) {

File fielName = new File(pathName);

File newFielName = new File(newPathName);

File newParentFile = newFielName.getParentFile();

if (!fielName.exists()) {

return false;

}

if (!newParentFile.exists()) {

newParentFile.mkdirs();

}

try {

Bitmap mBitmap = createFromUri(context, Uri.fromFile(fielName)

.toString(), 2 * maxXY, 2 * maxXY, 0, null);

if (mBitmap == null) {

return false;

}

Bitmap b = null;

if (mBitmap.getWidth() > mBitmap.getHeight()

&& mBitmap.getWidth() > maxXY) {

int tempHiget = maxXY * mBitmap.getHeight()

/ mBitmap.getWidth();

b = ThumbnailUtils.extractThumbnail(mBitmap, maxXY, tempHiget);

} else if (mBitmap.getHeight() > mBitmap.getWidth()

&& mBitmap.getHeight() > maxXY) {

int tempWidth = maxXY * mBitmap.getWidth()

/ mBitmap.getHeight();

b = ThumbnailUtils.extractThumbnail(mBitmap, tempWidth, maxXY);

}

if (b != null && mBitmap != b) {

mBitmap.recycle();

mBitmap = b;

}

saveOutput(context, mBitmap, newFielName);

return true;

} catch (Exception e) {

if (newFielName.exists()) {

newFielName.delete();

}

}

return false;

}

/**

* 从文件或Uri获得Bitmap 限制像素大小(maxResolutionX*maxResolutionY)

* 限制最小边长min(maxResolutionX*maxResolutionY)/2

*/

private static final Bitmap createFromUri(Context context, String uri,

int maxResolutionX, int maxResolutionY, long cacheId,

ClientConnectionManager connectionManager) throws IOException,

URISyntaxException, OutOfMemoryError {

final BitmapFactory.Options ptions = new BitmapFactory.Options();

options.inScaled = false;

options.inPreferredConfig = Bitmap.Config.RGB_565;

options.inDither = true;

Bitmap bitmap = null;

// Get the input stream for computing the sample size.

BufferedInputStream bufferedInput = null;

if (uri.startsWith(ContentResolver.SCHEME_CONTENT)

|| uri.startsWith(ContentResolver.SCHEME_FILE)) {

// Get the stream from a local file.

bufferedInput = new BufferedInputStream(context

.getContentResolver().openInputStream(Uri.parse(uri)),

16384);

} else {

return null;

}

// Compute the sample size, i.e., not decoding real pixels.

if (bufferedInput != null) {

options.inSampleSize = computeSampleSize(bufferedInput,

maxResolutionX, maxResolutionY);

} else {

return null;

}

// Get the input stream again for decoding it to a bitmap.

bufferedInput = null;

if (uri.startsWith(ContentResolver.SCHEME_CONTENT)

|| uri.startsWith(ContentResolver.SCHEME_FILE)) {

// Get the stream from a local file.

bufferedInput = new BufferedInputStream(context

.getContentResolver().openInputStream(Uri.parse(uri)),

16384);

} else {

return null;

}

// Decode bufferedInput to a bitmap.

if (bufferedInput != null) {

options.inDither = false;

options.inJustDecodeBounds = false;

Thread timeoutThread = new Thread("BitmapTimeoutThread") {

public void run() {

try {

Thread.sleep(6000);

options.requestCancelDecode();

} catch (InterruptedException e) {

}

}

};

timeoutThread.start();

bitmap = BitmapFactory.decodeStream(bufferedInput, null, options);

closeSilently(bufferedInput);

}

return bitmap;

}

/** 计算SampleSize【1】 */

private static int computeSampleSize(InputStream stream,

int maxResolutionX, int maxResolutionY) {

BitmapFactory.Options ptions = new BitmapFactory.Options();

options.inJustDecodeBounds = true;

BitmapFactory.decodeStream(stream, null, options);

int maxNumOfPixels = maxResolutionX * maxResolutionY;

int minSideLength = Math.min(maxResolutionX, maxResolutionY) / 2;

return UtilscomputeSampleSize(options, minSideLength, maxNumOfPixels);

}

/** 计算SampleSize【2】 */

private static int UtilscomputeSampleSize(BitmapFactory.Options options,

int minSideLength, int maxNumOfPixels) {

int initialSize = computeInitialSampleSize(options, minSideLength,

maxNumOfPixels);

int roundedSize;

if (initialSize <= 8) {

roundedSize = 1;

while (roundedSize < initialSize) {

roundedSize <<= 1;

}

} else {

roundedSize = (initialSize + 7) / 8 * 8;

}

return roundedSize;

}

/** 计算SampleSize【3】 */

private static int computeInitialSampleSize(BitmapFactory.Options options,

int minSideLength, int maxNumOfPixels) {

final int UNCONSTRAINED = -1;

double w = options.outWidth;

double h = options.outHeight;

int lowerBound = (maxNumOfPixels == UNCONSTRAINED) ? 1 : (int) Math

.ceil(Math.sqrt(w * h / maxNumOfPixels));

int upperBound = (minSideLength == UNCONSTRAINED) ? 128 : (int) Math

.min(Math.floor(w / minSideLength),

Math.floor(h / minSideLength));

if (upperBound < lowerBound) {

// return the larger one when there is no overlapping zone.

return lowerBound;

}

if ((maxNumOfPixels == UNCONSTRAINED)

&& (minSideLength == UNCONSTRAINED)) {

return 1;

} else if (minSideLength == UNCONSTRAINED) {

return lowerBound;

} else {

return upperBound;

}

}

/** 保存Bitmap到Uri地址【content:// or file://;"image/*" or "JPEG"】 */

private static void saveOutput(Context context, Bitmap mBitmap,

File newFielName) {

OutputStream utputStream = null;

try {

utputStream = context.getContentResolver().openOutputStream(

Uri.fromFile(newFielName));

if (outputStream != null) {

mBitmap.compress(Bitmap.CompressFormat.valueOf("JPEG"), 85,

outputStream);

}

} catch (IOException ex) {

} finally {

closeSilently(outputStream);

if (mBitmap != null) {

mBitmap.recycle();

mBitmap = null;

}

}

}

/** 关闭流文件 */

private static void closeSilently(Closeable c) {

if (c == null)

return;

try {

c.close();

} catch (Throwable t) {

}

}

}

xml 代码:

android:layout_width="match_parent"

android:layout_height="match_parent"

android:background="#f0f0f0"

android:orientation="vertical" >

android:layout_width="match_parent"

android:layout_height="wrap_content"

android:layout_gravity="top"

android:background="#006dba"

android:padding="5dip" >

android:id="@+id/backs"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:drawableLeft="@drawable/back"

android:paddingBottom="5dip"

android:paddingLeft="5dip"

android:paddingRight="20dip"

android:paddingTop="5dip" />

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:layout_centerInParent="true"

android:layout_weight="1"

android:text="快捷收银"

android:textColor="#ffffff"

android:textSize="20sp" />

android:layout_width="match_parent"

android:layout_height="match_parent"

>

android:layout_width="match_parent"

android:layout_height="match_parent"

android:orientation="vertical"

android:padding="10dip"

>

android:layout_width="match_parent"

android:layout_height="wrap_content"

android:paddingBottom="10dip"

android:orientation="horizontal"

>

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="商户名称:"

android:textColor="#000000"

/>

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:id="@+id/shanghuname"

android:background="@drawable/xian"

/>

android:layout_width="100dip"

android:layout_height="100dip"

android:id="@+id/images"

android:scaleType="centerInside"

android:src="@drawable/chongzhi"

/>

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
实现这个功能需要以下几个步骤: 1. 在 AndroidManifest.xml 文件中添加相机和文件读写权限。 ``` <uses-permission android:name="android.permission.CAMERA"/> <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/> ``` 2. 创建一个拍照按钮,并在点击事件中调用系统相机。 ```java // 启动系统相机 public void startCamera() { Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); if (intent.resolveActivity(getPackageManager()) != null) { File photoFile = createImageFile(); if (photoFile != null) { Uri photoUri = FileProvider.getUriForFile(this, "com.example.fileprovider", photoFile); intent.putExtra(MediaStore.EXTRA_OUTPUT, photoUri); startActivityForResult(intent, REQUEST_CODE_CAMERA); } } } // 创建图片文件 public File createImageFile() { String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date()); String imageFileName = "JPEG_" + timeStamp + "_"; File storageDir = getExternalFilesDir(Environment.DIRECTORY_PICTURES); try { File imageFile = File.createTempFile(imageFileName, ".jpg", storageDir); mCurrentPhotoPath = imageFile.getAbsolutePath(); return imageFile; } catch (IOException e) { e.printStackTrace(); } return null; } // 处理拍照结果 @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { if (requestCode == REQUEST_CODE_CAMERA && resultCode == RESULT_OK) { String photoPath = mCurrentPhotoPath; savePhotoPath(photoPath); // 将照片路径保存到数据库 mAdapter.addData(photoPath); // 将照片路径添加到 RecyclerView 中显示 } } ``` 3. 在 Activity 中创建一个 RecyclerView,并通过 Adapter 将数据绑定到 RecyclerView 上。 ```java // 初始化 RecyclerView public void initRecyclerView() { mRecyclerView = findViewById(R.id.recyclerview); mRecyclerView.setLayoutManager(new LinearLayoutManager(this)); mAdapter = new PhotoAdapter(this); mRecyclerView.setAdapter(mAdapter); } // 创建 Adapter public class PhotoAdapter extends RecyclerView.Adapter<PhotoAdapter.ViewHolder> { private Context mContext; private List<String> mPhotoPaths; public PhotoAdapter(Context context) { mContext = context; mPhotoPaths = new ArrayList<>(); } public void setData(List<String> photoPaths) { mPhotoPaths.clear(); mPhotoPaths.addAll(photoPaths); notifyDataSetChanged(); } public void addData(String photoPath) { mPhotoPaths.add(0, photoPath); notifyItemInserted(0); mRecyclerView.scrollToPosition(0); } @Override public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { View view = LayoutInflater.from(mContext).inflate(R.layout.item_photo, parent, false); return new ViewHolder(view); } @Override public void onBindViewHolder(ViewHolder holder, int position) { String photoPath = mPhotoPaths.get(position); Glide.with(mContext).load(photoPath).into(holder.ivPhoto); } @Override public int getItemCount() { return mPhotoPaths.size(); } public class ViewHolder extends RecyclerView.ViewHolder { ImageView ivPhoto; public ViewHolder(View itemView) { super(itemView); ivPhoto = itemView.findViewById(R.id.iv_photo); } } } ``` 4. 将拍摄的照片路径保存到数据库中。 ```java // 将照片路径保存到数据库 public void savePhotoPath(String photoPath) { SQLiteDatabase db = mDbHelper.getWritableDatabase(); ContentValues values = new ContentValues(); values.put(PhotoEntry.COLUMN_NAME_PATH, photoPath); db.insert(PhotoEntry.TABLE_NAME, null, values); db.close(); } ``` 5. 在 Activity 的 onCreate() 方法中初始化 RecyclerView 和数据库。 ```java @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); initRecyclerView(); mDbHelper = new PhotoDbHelper(this); loadPhotoPaths(); // 从数据库中加载照片路径并显示到 RecyclerView 上 } ``` 6. 从数据库中加载照片路径并显示到 RecyclerView 上。 ```java // 从数据库中加载照片路径并显示到 RecyclerView 上 public void loadPhotoPaths() { SQLiteDatabase db = mDbHelper.getReadableDatabase(); String[] projection = { PhotoEntry._ID, PhotoEntry.COLUMN_NAME_PATH }; Cursor cursor = db.query( PhotoEntry.TABLE_NAME, projection, null, null, null, null, PhotoEntry._ID + " DESC" ); List<String> photoPaths = new ArrayList<>(); while (cursor.moveToNext()) { String photoPath = cursor.getString(cursor.getColumnIndexOrThrow(PhotoEntry.COLUMN_NAME_PATH)); photoPaths.add(photoPath); } mAdapter.setData(photoPaths); cursor.close(); db.close(); } ``` 这样就可以实现在 Android App 中调用系统相机后拍照,将照片路径信息存到数据库,并在 RecyclerView 显示拍到的照片
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值