android - 上传前压缩相机图像

标签 android image upload camera compression

我正在使用此代码(来自 www.internetria.com)拍照并上传到服务器:

创建:

Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
Uri output = Uri.fromFile(new File(foto));
intent.putExtra(MediaStore.EXTRA_OUTPUT, output);
startActivityForResult(intent, TAKE_PICTURE);

onActivityResult:

ImageView iv = (ImageView) findViewById(R.id.imageView1);
        iv.setImageBitmap(BitmapFactory.decodeFile(foto));

        File file = new File(foto);
        if (file.exists()) {
            UploaderFoto nuevaTarea = new UploaderFoto();
            nuevaTarea.execute(foto);
        }
        else
            Toast.makeText(getApplicationContext(), "No se ha realizado la foto", Toast.LENGTH_SHORT).show();

上传者照片:

ProgressDialog pDialog;
String miFoto = "";

@Override
protected Void doInBackground(String... params) {
    miFoto = params[0];
    try { 
        HttpClient httpclient = new DefaultHttpClient();
        httpclient.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
        HttpPost httppost = new HttpPost("http://servidor.com/up.php");
        File file = new File(miFoto);
        MultipartEntity mpEntity = new MultipartEntity();
        ContentBody foto = new FileBody(file, "image/jpeg");
        mpEntity.addPart("fotoUp", foto);
        httppost.setEntity(mpEntity);
        httpclient.execute(httppost);
        httpclient.getConnectionManager().shutdown();
    } catch (Exception e) {
        e.printStackTrace();
    }
    return null;
}

而且我想压缩图片,因为尺寸太大了。

我不知道如何将 bitmap.compress(Bitmap.CompressFormat.JPEG, 70, fos); 添加到我的应用中

最佳答案

请看这里:ByteArrayOutputStream to a FileBody

按照这些思路应该可以工作:

替换

File file = new File(miFoto);
ContentBody foto = new FileBody(file, "image/jpeg");

Bitmap bmp = BitmapFactory.decodeFile(miFoto)
ByteArrayOutputStream bos = new ByteArrayOutputStream();
bmp.compress(CompressFormat.JPEG, 70, bos);
InputStream in = new ByteArrayInputStream(bos.toByteArray());
ContentBody foto = new InputStreamBody(in, "image/jpeg", "filename");

如果文件大小仍然是个问题,除了压缩图片之外,您可能还需要缩放图片。

关于android - 上传前压缩相机图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19594152/

相关文章:

java - PDF 中的图像为黑色

ios - 在纵向模式下拍摄的图像选择器 (UIImagePickerController) 中的照片显示拉伸(stretch) - Xcode 11/SwiftUI

Python 多处理脚本无限期挂起

image - Intervention\Image\Exception\ImageNotWritableException 使用 Laravel 4

maven - gradle始终使用{user.home}/repository作为Maven本地缓存

android - 在 Android 应用上的 Google map 中执行硬编码搜索

android - 安装 apk 时出现 java.lang.SecurityException

java - 如何监控文件上传进度?

java - 比较两个 ArrayLists,删除匹配的项

java - 如何在NavigationView中的textView中设置文本