上傳圖片選擇方式
以Base64的方式進(jìn)行上傳
//需要將文件或者bitmap轉(zhuǎn)化為String字符串
public String file2String(String path) {
File file = new File(path);
String string = null;
FileInputStream inputFile = null;
try {
inputFile = new FileInputStream(file);
byte[] buffer = new byte[(int) file.length()];
inputFile.read(buffer);
inputFile.close();
string = Base64.encodeToString(buffer, Base64.DEFAULT);
} catch (IOException e) {
e.printStackTrace();
}
return string;
}
public String bitmap2String(String path) {
Bitmap bitmap = BitmapFactory.decodeFile(path);
ByteArrayOutputStream bos=new ByteArrayOutputStream();
if (bitmap != null) {
bitmap.compress(Bitmap.CompressFormat.JPEG, 40, bos);
}
byte[] bytes=bos.toByteArray();
String string = Base64.encodeToString(bytes, Base64.DEFAULT);
return string;
}
獲取圖片uri
根據(jù)相對(duì)路徑(/storage/emulated/0/Pictures/IMG_20171108_180509.jpg)轉(zhuǎn)為URI:content://media/external/images/media
private Uri getImageContentUri(String filePath) {
if (TextUtils.isEmpty(filePath)) {
return null;
}
Cursor cursor = App.getInstance().getContentResolver().query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
new String[]{MediaStore.Images.Media._ID}, MediaStore.Images.Media.DATA + "=? ",
new String[]{filePath}, null);
if (cursor != null && cursor.moveToFirst()) {
int id = cursor.getInt(cursor.getColumnIndex(MediaStore.MediaColumns._ID));
Uri baseUri = Uri.parse("content://media/external/images/media");
cursor.close();
return Uri.withAppendedPath(baseUri, "" + id);
} else {
if (!TextUtils.isEmpty(filePath)) {
ContentValues values = new ContentValues();
values.put(MediaStore.Images.Media.DATA, filePath);
return App.getInstance().getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
} else {
return null;
}
}
}
通過(guò)吊起相機(jī)進(jìn)行拍照
// 這個(gè)注意權(quán)限問(wèn)題
private void takePhoto() {
String SDState = Environment.getExternalStorageState();
if (SDState.equals(Environment.MEDIA_MOUNTED)) {
tempFile = getPhotoFile();
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
// 指定調(diào)用相機(jī)拍照后照片的儲(chǔ)存路徑
intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(tempFile));
startActivityForResult(intent, REQUEST_CODE_CAMERA);
} else {
Toast.makeText(this, "no SD card!", Toast.LENGTH_LONG).show();
}
}
// 獲取拍照保存的路徑
private File getPhotoFile() {
// String path =
Environment.getExternalStorageDirectory().getAbsolutePath();
File file = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
Date date = new Date(System.currentTimeMillis());
SimpleDateFormat dateFormat = new SimpleDateFormat("'IMG'_yyyyMMdd_HHmmss");
String format = dateFormat.format(date);
return new File(file.getPath(), format + ".jpg");
}
通過(guò)打開(kāi)相冊(cè)進(jìn)行選擇圖片
private void pickPhoto() {
// Intent intent = new Intent(Intent.ACTION_PICK, null);
// intent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");
Intent intent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(intent, REQUEST_CODE_PHOTO);
}
圖片壓縮方法
質(zhì)量壓縮方法
/**
* 質(zhì)量壓縮方法
*
* @param image
* @return
*/
private Bitmap compressImage(Bitmap image) {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
image.compress(Bitmap.CompressFormat.JPEG, 100, baos);// 質(zhì)量壓縮方法,這里100表示不壓縮,把壓縮后的數(shù)據(jù)存放到baos中
int options = 100;
while (baos.toByteArray().length / 1024 > 100) { // 循環(huán)判斷如果壓縮后圖片是否大于100kb,大于繼續(xù)壓縮
baos.reset();// 重置baos即清空baos
image.compress(Bitmap.CompressFormat.JPEG, options, baos);// 這里壓縮options%沐祷,把壓縮后的數(shù)據(jù)存放到baos中
options -= 10;// 每次都減少10
}
ByteArrayInputStream isBm = new ByteArrayInputStream(baos.toByteArray());// 把壓縮后的數(shù)據(jù)baos存放到ByteArrayInputStream中
return BitmapFactory.decodeStream(isBm, null, null);
}
//======================================
/**
* 圖片壓縮方法:(使用compress的方法)
* <p/>
* <br>
* <b>說(shuō)明</b> 如果bitmap本身的大小小于maxSize蒂阱,則不作處理
*
* @param bitmap 要壓縮的圖片
* @param maxSize 壓縮后的大小鸵熟,單位kb
*/
private Bitmap compress(Bitmap bitmap, double maxSize) {
// 將bitmap放至數(shù)組中晒奕,意在獲得bitmap的大型薄(與實(shí)際讀取的原文件要大)
ByteArrayOutputStream baos = new ByteArrayOutputStream();
// 格式揍鸟、質(zhì)量兄裂、輸出流
bitmap.compress(Bitmap.CompressFormat.PNG, 70, baos);
byte[] b = baos.toByteArray();
// 將字節(jié)換成KB
double mid = b.length / 1024;
// 獲取bitmap大小 是允許最大大小的多少倍
double i = mid / maxSize;
// 判斷bitmap占用空間是否大于允許最大空間 如果大于則壓縮 小于則不壓縮
if (i > 1) {
// 縮放圖片 此處用到平方根 將寬帶和高度壓縮掉對(duì)應(yīng)的平方根倍
// (保持寬高不變,縮放后也達(dá)到了最大占用空間的大醒粼濉)
// scale方法是下面的scale方法
bitmap = scale(bitmap, bitmap.getWidth() / Math.sqrt(i),
bitmap.getHeight() / Math.sqrt(i));
}
return bitmap;
}
圖片縮放方法晰奖,縮放到指定的長(zhǎng)和寬
/**
* 圖片的縮放方法
*
* @param src :源圖片資源
* @param newWidth :縮放后寬度
* @param newHeight :縮放后高度
*/
private Bitmap scale(Bitmap src, double newWidth, double newHeight) {
// 記錄src的寬高
float width = src.getWidth();
float height = src.getHeight();
// 創(chuàng)建一個(gè)matrix容器
Matrix matrix = new Matrix();
// 計(jì)算縮放比例
float scaleWidth = ((float) newWidth) / width;
float scaleHeight = ((float) newHeight) / height;
// 開(kāi)始縮放
matrix.postScale(scaleWidth, scaleHeight);
// 創(chuàng)建縮放后的圖片
return Bitmap.createBitmap(src, 0, 0, (int) width, (int) height,
matrix, true);
}
按照比例進(jìn)行壓縮
/**
* 圖片按比例大小壓縮方法
*
* @param srcPath (根據(jù)路徑獲取圖片并壓縮)
* @return
*/
private Bitmap getOptimizedImage(String srcPath) {
// Log.d(TAG, "getOptimizedImage --> isInMainThread " + Utils.isInMainThread());
BitmapFactory.Options newOpts = new BitmapFactory.Options();
// 開(kāi)始讀入圖片,此時(shí)把options.inJustDecodeBounds 設(shè)回true了
newOpts.inJustDecodeBounds = true;
Bitmap bitmap = BitmapFactory.decodeFile(srcPath, newOpts);// 此時(shí)返回bm為空
newOpts.inJustDecodeBounds = false;
int w = newOpts.outWidth;
int h = newOpts.outHeight;
// 現(xiàn)在主流手機(jī)比較多是800*480分辨率腥泥,所以高和寬我們?cè)O(shè)置為
float hh = 800;// 這里設(shè)置高度為800f
float ww = 480;// 這里設(shè)置寬度為480f
// 縮放比畅涂。由于是固定比例縮放,只用高或者寬其中一個(gè)數(shù)據(jù)進(jìn)行計(jì)算即可
int be = 1;// be=1表示不縮放
if (w > h && w > ww) {// 如果寬度大的話(huà)根據(jù)寬度固定大小縮放
be = (int) (newOpts.outWidth / ww);
} else if (w < h && h > hh) {// 如果高度高的話(huà)根據(jù)寬度固定大小縮放
be = (int) (newOpts.outHeight / hh);
}
if (be <= 0)
be = 1;
newOpts.inSampleSize = be;// 設(shè)置縮放比例
// 重新讀入圖片道川,注意此時(shí)已經(jīng)把options.inJustDecodeBounds 設(shè)回false了
bitmap = BitmapFactory.decodeFile(srcPath, newOpts);
return compress(bitmap, 500L);// 壓縮好比例大小后再進(jìn)行質(zhì)量壓縮
}
注意:
在做圖片壓縮時(shí)盡量將壓縮操作放在子線(xiàn)程進(jìn)行處理午衰,因?yàn)閴嚎s過(guò)程比較耗時(shí),可能會(huì)拋出ANR