【问题标题】:Unable to resize image using Picasso无法使用毕加索调整图像大小
【发布时间】:2018-04-27 20:39:28
【问题描述】:

您好,我无法使用 Picasso 调整图像大小。我想调整图像大小并将其发送到服务器。我已将图像保存到我的内部目录并使用 mCurrentPhotoPath 访问它。该文件已上传到服务器,但未调整大小。任何帮助表示赞赏。

private File createImageFile() throws IOException {

    OutputStream outStream = null;
    // Create an image file name
    String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
    String imageFileName = "JPEG_" + timeStamp + "_";

    File storageDir = getExternalFilesDir(Environment.DIRECTORY_PICTURES);
    File image = File.createTempFile(
                imageFileName,  /* prefix */
                ".jpg",         /* suffix */
                storageDir      /* directory */
        );
    mCurrentPhotoPath = image.getAbsolutePath();
    try {
        outStream = new FileOutputStream(mCurrentPhotoPath);

        Bitmap bitmap = Picasso.get()
                               .load(mCurrentPhotoPath)
                               .resize(80, 80).fit()
                               .centerInside().get();
        bitmap = getResizedBitmap(bitmap,20);

        bitmap.compress(Bitmap.CompressFormat.PNG, 0, outStream);

        outStream.flush();
        outStream.close();
        // Save a file: path for use with ACTION_VIEW intents

        Log.i("file path before", mCurrentPhotoPath);

    } catch (Exception e) {
        Log.i("exception", e.toString());
    }
    return image;
}   

public Bitmap getResizedBitmap(Bitmap image, int maxSize) {
    int width = image.getWidth();
    int height = image.getHeight();

    float bitmapRatio = (float) width / (float) height;
    if (bitmapRatio > 1) {
        width = maxSize;
        height = (int) (width / bitmapRatio);
    } else {
        height = maxSize;
        width = (int) (height * bitmapRatio);
    }
    return Bitmap.createScaledBitmap(image, width, height, true);
}

文件大小为 3 - 4 MB。我想要最大 600KB 的文件。

【问题讨论】:

  • 你可能想看看这个答案。这与您的问题不同,但这段代码具有调整大小、压缩照片甚至显示使用改造stackoverflow.com/a/50017766/3136282 将照片上传到服务器的示例代码

标签: android


【解决方案1】:

我希望您应该将图像压缩为 Base 64 字符串,然后按照以下代码发送到服务器,您必须在这里使用您的位图。

Bitmap bitmap=/*intialize bitmap by your image's bitmap*/;

ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 70, byteArrayOutputStream);
byte[] byteArray = byteArrayOutputStream.toByteArray();

String encodedImage1 = Base64.encodeToString(byteArray, Base64.DEFAULT);

// encodedImage1 for passing to server

谢谢

【讨论】:

  • 我正在使用多部分请求上传文件,所以我不想将图像压缩到 base64
  • multipart 已弃用,停止使用。
  • 我正在使用“net.gotev:uploadservice:3.1”。是否已弃用?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-01-08
  • 1970-01-01
  • 2014-03-20
  • 2014-01-16
  • 1970-01-01
相关资源
最近更新 更多