0

I have this code that can compress a selected image in the gallery which is very useful when you want to allow the user to add a profile picture. this code works fine but I would like the compressed image to be saved in the shared preferences in order to be persistent.

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

I have looked at all these answers but none deals specifically with the question Que1 Que2 Que3 Que4 Que5

help me how do i record a compressed image

2 Answers2

0

I would not recommend you to do this at all, since you can just save an image to the storage of your phone. However if you really want to do this...

You can convert your image to a byte[] byte array. Then convert it to a Base64 string.

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

Then store it using:

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

Then you can use preferences.getString("image", ""); to get the image back. Do a Base64.decode and convert it back to the image.

However, I would recommend you to think about the architecture of your application. Doing this sounds just so wrong.

Maybe this is a better option for you: https://stackoverflow.com/a/17674787/5457878

gi097
  • 7,313
  • 3
  • 27
  • 49
  • what will be the best way to allow the user to put a light photo on his profile –  Jul 25 '18 at 07:38
  • Well, it depends if your application will support multiple users. If not, I would just save the image to the `/data` folder of the app. – gi097 Jul 25 '18 at 07:39
0

Method to encode your bitmap into string 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;
}

bitmap inside this method like something in your preference:

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

**display your image just anywhere, convert it into a bitmap again **

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