如何以共享首选项保存压缩图像?

时间:2018-07-25 07:20:16

标签: android image sharedpreferences

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

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];
}

我查看了所有这些答案,但没有一个问题专门针对Que1 Que2 Que3 Que4 Que5

帮助我如何记录压缩图像

2 个答案:

答案 0 :(得分:0)

我完全不建议您执行此操作,因为您可以将图像保存到手机的存储器中。但是,如果您真的要这样做...

您可以将图像转换为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

答案 1 :(得分:0)

将位图编码为字符串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);
}