一、圖片壓縮的必要性
在移動應用開發中,圖片上傳是很常見的操作,但是大圖上傳的時間和流量不只會浪費用戶的時間和流量,而且還會對伺服器造成負擔,因為伺服器需要承載大量的數據,如果全部是原圖的話,肯定會對伺服器的性能造成一定的影響。為了緩解這樣的狀況,處理圖片上傳就成了一項非常重要的內容。
所以,在進行圖片上傳之前,我們需要對圖片進行一些必要的處理,這裡講解一下android源碼是如何實現圖片壓縮和上傳的。
二、圖片的處理流程
在Android中,處理圖片上傳的步驟大概分為以下幾個方面:
1、選擇圖片
首先,需要使用系統自帶的圖庫或者相機等工具選擇一個圖片進行上傳。
private void selectImage() {
final CharSequence[] items =
{ "從相冊選取", "拍照" };
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("選擇圖片來源:");
builder.setItems(items, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int item) {
if (items[item].equals("從相冊選取")) {
Intent intent = new Intent(Intent.ACTION_PICK, null);
intent.setDataAndType(
MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
"image/*");
startActivityForResult(intent, IMAGE_PICKER_SELECT);
} else if (items[item].equals("拍照")) {
Intent intent = new Intent(
MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent, IMAGE_CAPTURE_SELECT);
}
}
});
builder.create().show();
}
2、先對圖片進行壓縮處理
使用Android提供的Bitmap類獲取原圖,並進行相應的處理,代碼如下:
private Bitmap getSmallBitmap(String filePath) {
final BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeFile(filePath, options);
options.inSampleSize = calculateInSampleSize(options, 480, 800);
options.inJustDecodeBounds = false;
Bitmap bitmap = BitmapFactory.decodeFile(filePath, options);
return bitmap;
}
private int calculateInSampleSize(BitmapFactory.Options options,
int reqWidth, int reqHeight) {
final int height = options.outHeight;
final int width = options.outWidth;
int inSampleSize = 1;
if (height > reqHeight || width > reqWidth) {
final int heightRatio = Math.round((float) height
/ (float) reqHeight);
final int widthRatio = Math.round((float) width / (float) reqWidth);
inSampleSize = heightRatio < widthRatio ? heightRatio : widthRatio;
}
return inSampleSize;
}
3、將處理後的圖片上傳到伺服器
將圖像壓縮後,再將之上傳到伺服器即可,以下是上傳過程的代碼:
private void upload(String path) {
RequestBody requestBody = new MultipartBody.Builder().setType(MultipartBody.FORM)
.addFormDataPart("username", "testuser")
.addFormDataPart("password", "testpwd")
.addFormDataPart("file", path.substring(path.lastIndexOf("/") + 1),
RequestBody.create(MediaType.parse("application/octet-stream"),
new File(path)))
.build();
Request request = new Request.Builder()
.url("http://your.upload.api/url")
.post(requestBody)
.build();
OkHttpClient client = new OkHttpClient();
client.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
e.printStackTrace();
}
@Override
public void onResponse(Call call, Response response) throws IOException {
if (response.isSuccessful()) {
Log.d(TAG, response.body().string());
} else {
throw new IOException("Unexpected code " + response);
}
}
});
}
三、總結
本文介紹了Android源碼中實現圖片壓縮和上傳的流程。通過對圖片進行壓縮處理,可以保證上傳的圖片大小變小,而且還可以減輕伺服器的壓力。通過示例代碼,希望能夠幫助讀者更好地理解圖片上傳的流程和代碼實現。
原創文章,作者:MRAZ,如若轉載,請註明出處:https://www.506064.com/zh-tw/n/149143.html