【问题标题】:How to Save a compressed image in shared preference?如何在共享首选项中保存压缩图像?
【发布时间】:2018-07-25 07:20:15
【问题描述】:

我有这段代码可以压缩图库中的选定图像,这在您希望允许用户添加个人资料图片时非常有用。此代码工作正常,但我希望将压缩图像保存在共享首选项中以便持久。

public void chooseImage(View view) {
    Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
    intent.setType("image/*");
    startActivityForResult(intent, PICK_IMAGE_REQUEST);
}

public void compressImage(View view) {
    if (actualImage == null) {
        showError("Please choose an image!");
    } else {
        // Compress image in main thread using custom Compressor
        try {
            compressedImage = new Compressor(this)
                    .setMaxWidth(640)
                    .setMaxHeight(480)
                    .setQuality(75)
                    .setCompressFormat(Bitmap.CompressFormat.WEBP)
                    .setDestinationDirectoryPath(Environment.getExternalStoragePublicDirectory(
                            Environment.DIRECTORY_PICTURES).getAbsolutePath())
                    .compressToFile(actualImage);

            setCompressedImage();

        } catch (IOException e) {
            e.printStackTrace();
            showError(e.getMessage());
        }

    }
}

private void setCompressedImage() {
    compressedImageView.setImageBitmap(BitmapFactory.decodeFile(compressedImage.getAbsolutePath()));
    compressedSizeTextView.setText(String.format("Size : %s", getReadableFileSize(compressedImage.length())));

    Toast.makeText(this, "Compressed image save in " + compressedImage.getPath(), Toast.LENGTH_LONG).show();
    Log.d("Compressor", "Compressed image save in " + compressedImage.getPath());
}

private void clearImage() {
    actualImageView.setBackgroundColor(getRandomColor());
    compressedImageView.setImageDrawable(null);
    compressedImageView.setBackgroundColor(getRandomColor());
    compressedSizeTextView.setText("Size : -");
}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (requestCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK) {
        if (data == null) {
            showError("Failed to open picture!");
            return;
        }
        try {
            actualImage = FileUtil.from(this, data.getData());
            actualImageView.setImageBitmap(BitmapFactory.decodeFile(actualImage.getAbsolutePath()));
            actualSizeTextView.setText(String.format("Size : %s", getReadableFileSize(actualImage.length())));
            clearImage();
        } catch (IOException e) {
            showError("Failed to read picture data!");
            e.printStackTrace();
        }
    }
}

public void showError(String errorMessage) {
    Toast.makeText(this, errorMessage, Toast.LENGTH_SHORT).show();
}

private int getRandomColor() {
    Random rand = new Random();
    return Color.argb(100, rand.nextInt(256), rand.nextInt(256), rand.nextInt(256));
}

public String getReadableFileSize(long size) {
    if (size <= 0) {
        return "0";
    }
    final String[] units = new String[]{"B", "KB", "MB", "GB", "TB"};
    int digitGroups = (int) (Math.log10(size) / Math.log10(1024));
    return new DecimalFormat("#,##0.#").format(size / Math.pow(1024, digitGroups)) + " " + units[digitGroups];
}

我已经查看了所有这些答案,但没有一个专门针对Que1Que2Que3Que4Que5这个问题。

帮助我如何记录压缩图像

【问题讨论】:

  • 将位图转换为base64字符串,并将字符串保存到共享首选项
  • 将图像保存在共享首选项中。 1. 使用 base64 编码图像,我们得到输出为字符串 2. 将其保存在共享首选项中 3. 将 base64 字符串解码回图像,以使用图像
  • 在提供的问题中什么不起作用?哪里出错了?

标签: android image sharedpreferences


【解决方案1】:

我完全不建议您这样做,因为您可以将图像保存到手机的存储空间中。但是,如果您真的想要这样做......

您可以将图像转换为byte[] 字节数组。然后将其转换为Base64 字符串。

String encodedImg = Base64.encodeToString(bytes, Base64.DEFAULT);

然后使用以下方式存储它:

SharedPreferences.Editor editor = preferences.edit();
editor.putString("image", encodedImg);

然后您可以使用preferences.getString("image", ""); 来获取图像。执行Base64.decode 并将其转换回图像。

但是,我建议您考虑一下应用程序的架构。这样做听起来很不对。

也许这对你来说是一个更好的选择:https://stackoverflow.com/a/17674787/5457878

【讨论】:

  • 什么是允许用户在他的个人资料上放一张浅色照片的最佳方式
  • 嗯,这取决于您的应用程序是否支持多个用户。如果没有,我会将图像保存到应用程序的/data 文件夹中。
【解决方案2】:

将位图编码为字符串 base64 的方法-

public static String encodeTobase64(Bitmap image) {
Bitmap immage = image;
ByteArrayOutputStream baos = new ByteArrayOutputStream();
immage.compress(Bitmap.CompressFormat.PNG, 100, baos);
byte[] b = baos.toByteArray();
String imageEncoded = Base64.encodeToString(b, Base64.DEFAULT);

Log.d("Image Log:", imageEncoded);
return imageEncoded;
}

此方法中的位图就像您喜欢的一样:

SharedPreferences.Editor editor = myPrefrence.edit();
editor.putString("namePreferance", itemNAme);
editor.putString("imagePreferance", encodeTobase64(yourbitmap));
editor.commit();

**在任何地方显示您的图像,再次将其转换为位图**

public static Bitmap decodeBase64(String input) {
byte[] decodedByte = Base64.decode(input, 0);
return BitmapFactory
        .decodeByteArray(decodedByte, 0, decodedByte.length);
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-05-31
    • 2020-06-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多