【发布时间】:2018-05-23 09:04:47
【问题描述】:
目前我正在使用mulitpart/form-data 将图像上传到服务器。在 node.js 服务器端,图像的存储没有任何问题。但是将图片上传到服务器需要很多时间。我尝试在上传位图之前重新缩放它们,但在大多数情况下,图片上传的尺寸比原始图像大,例如 200kb 的图片变成了 400kb 之类的东西。所以,我想知道如何正确缩放位图并以高效的速度将它们高质量地上传到服务器?
位图缩放代码:
bmp = MediaStore.Images.Media.getBitmap(ctx.getContentResolver(), uri);
int maxSize=700;
int outWidth;
int outHeight;
int inWidth = bmp.getWidth();
int inHeight = bmp.getHeight();
if(inWidth > inHeight){
outWidth = maxSize;
outHeight = (inHeight * maxSize) / inWidth;
} else {
outHeight = maxSize;
outWidth = (inWidth * maxSize) / inHeight;
}
final Bitmap new_bitmap = Bitmap.createScaledBitmap(bmp, outWidth, outHeight, false);
将位图保存到存储中:
void saveImage(String imgName, Bitmap bm) throws IOException {
//Create Path to save Image
File file_path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES + "/Infinity"); //Creates app specific folder
file_path.mkdirs();
File imageFile = new File(file_path, imgName + ".png"); // Imagename.png
FileOutputStream out = new FileOutputStream(imageFile);
try {
bm.compress(Bitmap.CompressFormat.PNG, 100, out); // Compress Image
out.flush();
out.close();
// Tell the media scanner about the new file so that it is
// immediately available to the user.
MediaScannerConnection.scanFile(ctx, new String[]{imageFile.getAbsolutePath()}, null, new MediaScannerConnection.OnScanCompletedListener() {
public void onScanCompleted(String pathi, Uri uri) {
Log.i("ExternalStorage", "Scanned " + file_path + ":");
Log.i("ExternalStorage", "-> uri=" + uri);
parts.add(prepareFilePart("photo", pathi));
RequestBody description = createPartFromString(obji.toString());
FileUploadService service = ServiceGenerator.createService(FileUploadService.class);
Call<ResponseBody> call = service.uploadMultipleFilesDynamic(description, parts);
call.enqueue(new Callback<ResponseBody>() {
@Override
public void onResponse(Call<ResponseBody> call,
Response<ResponseBody> response) {
Log.v("Upload", "success");
Intent i=new Intent(ctx,Home_Screen.class);
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK|Intent.FLAG_ACTIVITY_NO_ANIMATION);
startActivity(i);
}
@Override
public void onFailure(Call<ResponseBody> call, Throwable t) {
if(t.getMessage()!=null) {
Log.e("Upload error:", t.getMessage());
Toast.makeText(ctx, t.getMessage(), Toast.LENGTH_LONG).show();
//Don't toast t.getMessage it would show the ip address which is bad
}
}
});
//Toast.makeText(ctx, "Downloaded Successfully", Toast.LENGTH_SHORT).show();
}
});
} catch (Exception e) {
throw new IOException();
}
}
【问题讨论】:
-
一个选项是压缩图像然后上传。也可以通过改造上传。
-
非常感谢您的关注,您能帮我压缩图像吗? @ZeeshanSardar
-
outWidth = maxSize;。你总是给它最大尺寸。即使在与较小。为什么? -
我只是在下面回答,希望对你有帮助。
-
您以 JPG 开头,以 PNG 结尾?
标签: android image-uploading android-bitmap