How to resize an image file in Android

In our last tutorial, we looked at how to build an Android app from scratch. We covered how to compress an image file in Android. If you have not seen the tutorial, I suggest you read it first.

In today’s tutorial, we will focus on how to resize an image file in Android programmatically.

Image resize in Android

You can resize an image in Android with one of the following options.

  1. Change the image dimension. 
  2. Change the quality value of an image.

Before we dive into the code, the scope of your project determines the best implementation to use.

Image resize in Android follows the steps below.

  1. Convert an image to a bitmap.
  2. Specify the new width and height of the resized image.
  3. Resize the image using the createScaledBitmap() method of the Bitmap class.
  4. Save the new bitmap to a new image file.

Image Resize Options

We can resize an image programmatically in Android using a simple Java code or with a third-party library.

You can see an example code on how to resize an image below. 

In building this Android application, we will use a third-party library we used in the previous tutorial.

Sample code example to resize a bitmap image in Android

// Load the original image file
Bitmap originalBitmap = BitmapFactory.decodeFile("path_to_image_file");

// Define the desired width and height for the resized image
int desiredWidth = 500;
int desiredHeight = 500;

// Resize the image using createScaledBitmap() method
Bitmap resizedBitmap = Bitmap.createScaledBitmap(originalBitmap, desiredWidth, desiredHeight, false);

// Save the resized bitmap to a new file
FileOutputStream outputStream = new FileOutputStream("path_to_resized_image_file");
resizedBitmap.compress(Bitmap.CompressFormat.JPEG, 100, outputStream);
outputStream.close();

Using Third-Party Libraries

There are several third-party libraries available that offer more advanced image resize techniques. These libraries often provide options to control the compression level, image dimensions, and quality. For this feature, we will use the Android library called Resizer.

implementation 'com.github.hkk595:Resizer:v1.5'

Android Image Resize UI

Below is the user interface for image compression in Andriod. 

Android Image Resize Code

If you have followed the previous tutorial, we covered how to create a new Android project in Android Studio.

We are going to create a new Activity page. I will name the file ResizeImageActivity.Java. Feel free to choose a name of your choice.

UI XML Layout code

We are going to create the UI mock-up image above using XML code. Below is the complete layout code. Please feel free to rewrite the code if you want to make changes to the code.

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#fafafa"
    tools:context=".home.ui.tools.featuresUI.ResizeImageActivity">

    <ScrollView
        android:layout_width="match_parent"
        android:layout_height="0dp"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintBottom_toTopOf="@id/adview_wrapper"
        android:scrollbars="none">

        <androidx.appcompat.widget.LinearLayoutCompat
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="vertical">

            <androidx.cardview.widget.CardView
                android:id="@+id/image_card"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                app:cardElevation="4dp"
                app:cardUseCompatPadding="true"
                app:cardCornerRadius="16dp">

                <FrameLayout
                    android:layout_width="match_parent"
                    android:layout_height="220dp"
                    android:orientation="vertical">

                    <androidx.appcompat.widget.AppCompatImageView
                        android:id="@+id/selected_image"
                        android:layout_width="match_parent"
                        android:layout_height="match_parent"
                        android:scaleType="centerCrop"/>

                    <androidx.appcompat.widget.AppCompatTextView
                        android:id="@+id/click_to_upload_image"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:layout_gravity="center"
                        android:text="CLICK TO UPLOAD IMAGE"
                        android:textStyle="bold"
                        android:textSize="16sp"
                        android:padding="16dp"/>

                    <androidx.appcompat.widget.AppCompatImageView
                        android:id="@+id/upload_image_icon"
                        android:layout_width="32dp"
                        android:layout_height="32dp"
                        android:src="@drawable/upload"
                        android:layout_gravity="bottom|end"
                        android:layout_margin="12dp"
                        android:visibility="gone"
                        android:scaleType="centerCrop"/>

                </FrameLayout>

            </androidx.cardview.widget.CardView>

            <androidx.appcompat.widget.LinearLayoutCompat
                android:id="@+id/row_container"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:orientation="vertical"
                app:layout_constraintTop_toBottomOf="@id/image_card"
                android:padding="8dp">

                <androidx.cardview.widget.CardView
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    app:cardUseCompatPadding="true"
                    app:cardCornerRadius="8dp"
                    android:elevation="2dp">

                    <RelativeLayout
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:padding="8dp">

                        <androidx.appcompat.widget.AppCompatTextView
                            android:layout_width="wrap_content"
                            android:layout_height="wrap_content"
                            android:text="Resize image by"
                            android:textColor="@color/black"
                            android:layout_centerVertical="true"
                            android:layout_alignParentStart="true"
                            android:textSize="15sp"/>

                        <androidx.appcompat.widget.LinearLayoutCompat
                            android:layout_width="wrap_content"
                            android:layout_height="wrap_content"
                            android:layout_alignParentEnd="true"
                            android:orientation="horizontal">

                            <RadioGroup
                                android:id="@+id/resize_group"
                                android:layout_width="wrap_content"
                                android:layout_height="wrap_content"
                                android:orientation="horizontal">

                                <androidx.appcompat.widget.AppCompatRadioButton
                                    android:id="@+id/resize_by_pixel"
                                    android:layout_width="wrap_content"
                                    android:layout_height="wrap_content"
                                    android:checked="true"
                                    android:textSize="15sp"
                                    android:text="Pixel"/>

                                <androidx.appcompat.widget.AppCompatRadioButton
                                    android:id="@+id/resize_by_pecentage"
                                    android:layout_width="wrap_content"
                                    android:layout_height="wrap_content"
                                    android:layout_marginStart="20dp"
                                    android:textSize="15sp"
                                    android:text="Percentage"/>

                            </RadioGroup>

                        </androidx.appcompat.widget.LinearLayoutCompat>

                    </RelativeLayout>

                </androidx.cardview.widget.CardView>

                <androidx.cardview.widget.CardView
                    android:id="@+id/by_dimension"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    app:cardUseCompatPadding="true"
                    app:cardCornerRadius="8dp"
                    android:elevation="2dp"
                    android:layout_marginTop="8dp">

                    <androidx.appcompat.widget.LinearLayoutCompat
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:padding="8dp"
                        android:orientation="horizontal">

                        <androidx.appcompat.widget.LinearLayoutCompat
                            android:layout_width="0dp"
                            android:layout_height="wrap_content"
                            android:layout_weight="5"
                            android:padding="8dp"
                            android:layout_marginEnd="4dp"
                            android:orientation="vertical">

                            <androidx.appcompat.widget.AppCompatTextView
                                android:layout_width="wrap_content"
                                android:layout_height="wrap_content"
                                android:text="Width (px)"
                                android:textSize="15sp"
                                android:textColor="@color/black"/>

                            <androidx.appcompat.widget.AppCompatEditText
                                android:id="@+id/resize_width"
                                android:layout_width="match_parent"
                                android:layout_height="wrap_content"
                                android:background="@drawable/border_corner"
                                android:inputType="number"
                                android:layout_marginTop="6dp"
                                android:padding="8dp"/>

                        </androidx.appcompat.widget.LinearLayoutCompat>

                        <androidx.appcompat.widget.LinearLayoutCompat
                            android:layout_width="0dp"
                            android:layout_height="match_parent"
                            android:layout_weight="1"
                            android:padding="8dp"
                            android:gravity="center"
                            android:orientation="vertical">

                            <androidx.appcompat.widget.AppCompatImageView
                                android:layout_width="wrap_content"
                                android:layout_height="wrap_content"
                                android:scaleType="center"
                                android:layout_marginTop="24dp"
                                android:src="@drawable/link"/>

                        </androidx.appcompat.widget.LinearLayoutCompat>

                        <androidx.appcompat.widget.LinearLayoutCompat
                            android:layout_width="0dp"
                            android:layout_height="wrap_content"
                            android:layout_weight="5"
                            android:padding="8dp"
                            android:layout_marginStart="4dp"
                            android:orientation="vertical">

                            <androidx.appcompat.widget.AppCompatTextView
                                android:layout_width="wrap_content"
                                android:layout_height="wrap_content"
                                android:text="Height (px)"
                                android:textSize="15sp"
                                android:textColor="@color/black"/>

                            <androidx.appcompat.widget.AppCompatEditText
                                android:id="@+id/resize_height"
                                android:layout_width="match_parent"
                                android:layout_height="wrap_content"
                                android:inputType="number"
                                android:background="@drawable/border_corner"
                                android:layout_marginTop="6dp"
                                android:padding="8dp"/>

                        </androidx.appcompat.widget.LinearLayoutCompat>

                    </androidx.appcompat.widget.LinearLayoutCompat>

                </androidx.cardview.widget.CardView>

                <androidx.cardview.widget.CardView
                    android:id="@+id/by_percentage"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    app:cardUseCompatPadding="true"
                    app:cardCornerRadius="8dp"
                    android:elevation="2dp"
                    android:layout_marginTop="8dp">

                    <androidx.appcompat.widget.LinearLayoutCompat
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:padding="12dp"
                        android:orientation="vertical">

                        <androidx.appcompat.widget.LinearLayoutCompat
                            android:layout_width="match_parent"
                            android:layout_height="wrap_content"
                            android:orientation="horizontal">

                            <androidx.appcompat.widget.AppCompatTextView
                                android:layout_width="wrap_content"
                                android:layout_height="wrap_content"
                                android:text="Quantity"
                                android:textStyle="bold"
                                android:textSize="15sp"
                                android:textColor="@color/black"/>

                            <androidx.appcompat.widget.AppCompatTextView
                                android:id="@+id/quantity_percent"
                                android:layout_width="wrap_content"
                                android:layout_height="wrap_content"
                                android:text="100%"
                                android:textSize="15sp"
                                android:layout_marginStart="12dp"
                                android:layout_marginEnd="12dp"
                                android:textColor="@color/black"/>

                        </androidx.appcompat.widget.LinearLayoutCompat>

                        <androidx.appcompat.widget.AppCompatSeekBar
                            android:id="@+id/seekbar"
                            android:layout_width="match_parent"
                            android:layout_height="wrap_content"
                            android:layout_marginTop="6dp"
                            android:progress="100"
                            android:max="100"/>

                    </androidx.appcompat.widget.LinearLayoutCompat>

                </androidx.cardview.widget.CardView>

                <androidx.cardview.widget.CardView
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    app:cardUseCompatPadding="true"
                    app:cardCornerRadius="8dp"
                    android:layout_marginEnd="4dp"
                    android:layout_marginStart="4dp"
                    android:elevation="2dp"
                    android:layout_marginTop="8dp">

                    <androidx.appcompat.widget.LinearLayoutCompat
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:padding="12dp"
                        android:orientation="vertical">

                        <androidx.appcompat.widget.AppCompatTextView
                            android:layout_width="wrap_content"
                            android:layout_height="wrap_content"
                            android:text="Image Format"
                            android:textStyle="bold"
                            android:textSize="15sp"
                            android:layout_marginBottom="18dp"
                            android:textColor="@color/black"/>

                        <nl.bryanderidder.themedtogglebuttongroup.ThemedToggleButtonGroup
                            android:id="@+id/file_format_options"
                            android:layout_width="match_parent"
                            android:layout_height="wrap_content"
                            app:toggle_selectableAmount="1"
                            app:justifyContent="center">

                            <nl.bryanderidder.themedtogglebuttongroup.ThemedButton
                                android:id="@+id/image_png"
                                android:layout_width="wrap_content"
                                android:layout_height="38dp"
                                app:toggle_selectedBackgroundColor="@color/my_accent"
                                app:toggle_selectedTextColor="@android:color/black"
                                app:toggle_text="PNG" />

                            <nl.bryanderidder.themedtogglebuttongroup.ThemedButton
                                android:id="@+id/image_jpg"
                                android:layout_width="wrap_content"
                                android:layout_height="38dp"
                                app:toggle_selectedBackgroundColor="@color/my_accent"
                                app:toggle_selectedTextColor="@android:color/black"
                                app:toggle_text="JPG" />

                            <nl.bryanderidder.themedtogglebuttongroup.ThemedButton
                                android:id="@+id/image_webp"
                                android:layout_width="wrap_content"
                                android:layout_height="38dp"
                                app:toggle_selectedBackgroundColor="@color/my_accent"
                                app:toggle_selectedTextColor="@android:color/black"
                                app:toggle_text="WEBP" />

                            <nl.bryanderidder.themedtogglebuttongroup.ThemedButton
                                android:id="@+id/image_bmp"
                                android:layout_width="wrap_content"
                                android:layout_height="38dp"
                                app:toggle_selectedBackgroundColor="@color/my_accent"
                                app:toggle_selectedTextColor="@android:color/black"
                                app:toggle_text="BMP" />

                        </nl.bryanderidder.themedtogglebuttongroup.ThemedToggleButtonGroup>

                    </androidx.appcompat.widget.LinearLayoutCompat>

                </androidx.cardview.widget.CardView>

                <androidx.cardview.widget.CardView
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    app:cardUseCompatPadding="true"
                    app:cardCornerRadius="8dp"
                    android:elevation="2dp"
                    android:layout_marginTop="8dp">

                    <androidx.appcompat.widget.LinearLayoutCompat
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:padding="12dp"
                        android:orientation="vertical">

                        <RelativeLayout
                            android:layout_width="match_parent"
                            android:layout_height="wrap_content">

                            <androidx.appcompat.widget.AppCompatTextView
                                android:layout_width="wrap_content"
                                android:layout_height="wrap_content"
                                android:text="@string/current"
                                android:textSize="15sp"
                                android:textStyle="bold"
                                android:layout_alignParentStart="true"
                                android:textColor="@color/black"/>

                            <androidx.appcompat.widget.LinearLayoutCompat
                                android:layout_width="wrap_content"
                                android:layout_height="wrap_content"
                                android:layout_alignParentEnd="true"
                                android:orientation="horizontal">

                                <androidx.appcompat.widget.AppCompatTextView
                                    android:id="@+id/current_image_resolution"
                                    android:layout_width="wrap_content"
                                    android:layout_height="wrap_content"
                                    android:text="524 x 320 px"
                                    android:textSize="15sp"
                                    android:layout_marginEnd="18dp"
                                    android:layout_alignParentStart="true"
                                    android:textColor="@color/black"/>

                                <androidx.appcompat.widget.AppCompatTextView
                                    android:id="@+id/current_image_size"
                                    android:layout_width="wrap_content"
                                    android:layout_height="wrap_content"
                                    android:text="18 KB"
                                    android:textSize="15sp"
                                    android:layout_marginEnd="12dp"
                                    android:layout_alignParentStart="true"
                                    android:textColor="@color/black"/>

                                <androidx.appcompat.widget.AppCompatTextView
                                    android:id="@+id/current_image_extension"
                                    android:layout_width="wrap_content"
                                    android:layout_height="wrap_content"
                                    android:text="PNG"
                                    android:textSize="15sp"
                                    android:layout_alignParentStart="true"
                                    android:textColor="@color/black"/>

                            </androidx.appcompat.widget.LinearLayoutCompat>

                        </RelativeLayout>

                        <RelativeLayout
                            android:id="@+id/second_row"
                            android:layout_width="match_parent"
                            android:layout_height="wrap_content"
                            android:visibility="gone"
                            android:layout_marginTop="16dp">

                            <androidx.appcompat.widget.AppCompatTextView
                                android:id="@+id/current_size"
                                android:layout_width="wrap_content"
                                android:layout_height="wrap_content"
                                android:text="Resize: "
                                android:textStyle="bold"
                                android:textSize="15sp"
                                android:layout_alignParentStart="true"
                                android:textColor="@color/black"/>

                            <androidx.appcompat.widget.LinearLayoutCompat
                                android:layout_width="wrap_content"
                                android:layout_height="wrap_content"
                                android:layout_alignParentEnd="true"
                                android:orientation="horizontal">

                                <androidx.appcompat.widget.AppCompatTextView
                                    android:id="@+id/new_image_resolution"
                                    android:layout_width="wrap_content"
                                    android:layout_height="wrap_content"
                                    android:text=""
                                    android:textSize="15sp"
                                    android:layout_marginEnd="18dp"
                                    android:layout_alignParentStart="true"
                                    android:textColor="@color/black"/>

                                <androidx.appcompat.widget.AppCompatTextView
                                    android:id="@+id/new_image_size"
                                    android:layout_width="wrap_content"
                                    android:layout_height="wrap_content"
                                    android:text=""
                                    android:textSize="15sp"
                                    android:layout_marginEnd="12dp"
                                    android:layout_alignParentStart="true"
                                    android:textColor="@color/black"/>

                                <androidx.appcompat.widget.AppCompatTextView
                                    android:id="@+id/new_image_extension"
                                    android:layout_width="wrap_content"
                                    android:layout_height="wrap_content"
                                    android:text=""
                                    android:textSize="15sp"
                                    android:layout_alignParentStart="true"
                                    android:textColor="@color/black"/>

                            </androidx.appcompat.widget.LinearLayoutCompat>

                        </RelativeLayout>

                    </androidx.appcompat.widget.LinearLayoutCompat>

                </androidx.cardview.widget.CardView>

            </androidx.appcompat.widget.LinearLayoutCompat>

        </androidx.appcompat.widget.LinearLayoutCompat>

    </ScrollView>

    <androidx.appcompat.widget.LinearLayoutCompat
        android:id="@+id/adview_wrapper"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="#fafafa"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintBottom_toBottomOf="parent"
        android:orientation="vertical">

        <androidx.appcompat.widget.LinearLayoutCompat
            android:layout_width="match_parent"
            android:layout_height="60dp"
            android:orientation="vertical">

        </androidx.appcompat.widget.LinearLayoutCompat>

        <RelativeLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginTop="12dp"
            android:padding="12dp">

            <androidx.appcompat.widget.LinearLayoutCompat
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:padding="12dp"
                android:layout_alignParentEnd="true"
                android:orientation="horizontal">

                <androidx.appcompat.widget.AppCompatImageView
                    android:id="@+id/bottom_image_picker"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:scaleType="centerCrop"
                    android:layout_marginEnd="21dp"
                    android:elevation="4dp"
                    android:src="@drawable/imageadd"/>

                <androidx.appcompat.widget.AppCompatImageView
                    android:id="@+id/save_resize_image"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:scaleType="centerCrop"
                    android:elevation="4dp"
                    android:src="@drawable/imagesave"/>

            </androidx.appcompat.widget.LinearLayoutCompat>


        </RelativeLayout>

    </androidx.appcompat.widget.LinearLayoutCompat>

</androidx.constraintlayout.widget.ConstraintLayout>

Image Resize Activity Java Page

Open the ResizeImageActivity.Java file, and copy and paste the code below into the file.

You can observe the following.

  1. We will use an image picker to select an image from the gallery or open the device camera preview to capture the image.
  2. The view instances from the layout file were stored using view binding.
  3. When a user selects or captures an image, display the image on an ImageView.
  4. Based on the resize option the user selects, it toggles the dimension and quality value.
  5. When the resize option is selected, the user can save the resized image.
public class ResizeImageActivity extends AppCompatActivity {

    private static final String TAG = ResizeImageActivity.class.getSimpleName();

    private IntentUtils intentUtils;

    private AppCompatTextView openImageDialog;

    private ActivityResizeImageBinding binding;

    private CardView byDimension;

    private CardView byPercentage;

    private RadioGroup radioGroup;

    private AppCompatEditText resizeWidth;

    private AppCompatEditText resizeHeight;

    private AppCompatImageView selectedImageView;

    private AppCompatImageView bottomPicker;

    private ThemedToggleButtonGroup themeGroup;

    private AppCompatTextView currentImageResolution, currentImageSize, currentImageExtension;

    private AppCompatTextView newImageResolution, newImageSize, newImageExtension;

    private LinearLayoutCompat rowContainerVisibility;

    private FileUtility fileUtility;

    private int hasDimensionChanged = 0;

    private int progressValue = 100;

    private AppCompatImageView saveResizedImage;

    private RelativeLayout secondRowForImageInfo;

    private AppCompatTextView qualityText;

    private AppCompatSeekBar qualitySeek;

    private boolean isResizeByPercent = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        binding = ActivityResizeImageBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());

        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        getSupportActionBar().setDisplayShowHomeEnabled(true);

        setTitle("Resize Image");

        byDimension = binding.byDimension;
        byPercentage = binding.byPercentage;

        themeGroup = binding.fileFormatOptions;

        //Image Quality
        qualityText = binding.quantityPercent;
        qualitySeek = binding.seekbar;
        onImageQualityChange();


        currentImageResolution = binding.currentImageResolution;
        currentImageSize = binding.currentImageSize;
        currentImageExtension = binding.currentImageExtension;

        saveResizedImage = binding.saveResizeImage;

        secondRowForImageInfo = binding.secondRow;

        newImageResolution = binding.newImageResolution;
        newImageSize = binding.newImageSize;
        newImageExtension = binding.newImageExtension;

        rowContainerVisibility = binding.rowContainer;
        rowContainerVisibility.setVisibility(View.GONE);

        selectedImageView = binding.selectedImage;

        resizeWidth = binding.resizeWidth;
        resizeHeight = binding.resizeHeight;

        radioGroup = binding.resizeGroup;
        radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup radioGroup, int id) {

                if (id == R.id.resize_by_pixel) {
                    byDimension.setVisibility(View.VISIBLE);
                    byPercentage.setVisibility(View.GONE);
                    isResizeByPercent = false;
                }
                if (id == R.id.resize_by_pecentage) {
                    byPercentage.setVisibility(View.VISIBLE);
                    byDimension.setVisibility(View.GONE);
                    isResizeByPercent = true;
                }
            }
        });


        openImageDialog = binding.clickToUploadImage;
        openImageDialog.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                openGallery();
                openImageDialog.setVisibility(View.GONE);
            }
        });

        bottomPicker = binding.bottomImagePicker;
        bottomPicker.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                openGallery();
                openImageDialog.setVisibility(View.GONE);
            }
        });

        //Save Image button action
        saveImageBtn();
    }

    private void onImageQualityChange() {
        qualitySeek.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean b) {
                qualityText.setText(String.valueOf(progress) + "%");
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {
            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {

                progressValue = seekBar.getProgress();

                StorageUtil storageUtil = new StorageUtil(ResizeImageActivity.this);
                String resizePath = storageUtil.createInnerFolderStorage("Resize");

                ResizeImageHelper helper = new ResizeImageHelper(ResizeImageActivity.this);
                File reFile = helper.resizeImageQuality(progressValue, fileUtility.getExtension(), fileUtility.getFilenameWithoutExtension(), resizePath, fileUtility.getUploadedFile());

                Picasso.get().load(reFile).networkPolicy(NetworkPolicy.NO_CACHE).memoryPolicy(MemoryPolicy.NO_CACHE).into(selectedImageView);
            }
        });
    }

    private void OnImageWidthResize() {
        resizeWidth.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                String newOutput = charSequence.toString();
                if (newOutput.equals("")) {
                    newOutput = "0";
                }

                int newImageWidth = Integer.parseInt(newOutput);
                //Resize the Image to a new size
                if (newImageWidth > 0) {

                    int heightImage = Integer.parseInt(Objects.requireNonNull(resizeHeight.getText()).toString());

                    secondRowForImageInfo.setVisibility(View.VISIBLE);
                    updateResizeImageInformation(newImageWidth, heightImage);
                }
            }

            @Override
            public void afterTextChanged(Editable editable) {

                String newOutput = editable.toString();
                if (newOutput.equals("")) {
                    newOutput = "0";
                }
                int newImageWidth = Integer.parseInt(newOutput);
                int heightImage = Integer.parseInt(Objects.requireNonNull(resizeHeight.getText()).toString());

                StorageUtil storageUtil = new StorageUtil(ResizeImageActivity.this);
                String store = storageUtil.createInnerFolderStorage("Resize");
                String fullPath = store + "/" + fileUtility.getFilename();
                File saveFile = new File(fullPath);

                String resolution = String.valueOf(newImageWidth) + " x " + String.valueOf(heightImage) + " px";
                String size = ConvertUtils.formatSize(saveFile.length());
                String extension = Files.getFileExtension(saveFile.getAbsolutePath());

                displayNewImageInformation(resolution, size, extension.toUpperCase());
            }

        });
    }

    private void onImageHeightResize() {
        resizeHeight.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                String newOutput = charSequence.toString();
                if (newOutput.equals("")) {
                    newOutput = "0";
                }
                int newImageHeight = Integer.parseInt(newOutput);
                int widthImage = Integer.parseInt(Objects.requireNonNull(resizeWidth.getText()).toString());

                //Resize the Image to a new size
                if (newImageHeight > 0) {
                    secondRowForImageInfo.setVisibility(View.VISIBLE);
                    updateResizeImageInformation(widthImage, newImageHeight);
                }
            }

            @Override
            public void afterTextChanged(Editable editable) {

                String newOutput = editable.toString();
                if (newOutput.equals("")) {
                    newOutput = "0";
                }

                int newImageHeight = Integer.parseInt(newOutput);
                int widthImage = Integer.parseInt(Objects.requireNonNull(resizeWidth.getText()).toString());
                StorageUtil storageUtil = new StorageUtil(ResizeImageActivity.this);
                String store = storageUtil.createInnerFolderStorage("Resize");
                String fullPath = store + "/" + fileUtility.getFilename();
                File saveFile = new File(fullPath);

                String resolution = String.valueOf(widthImage) + " x " + String.valueOf(newImageHeight) + " px";
                String size = ConvertUtils.formatSize(saveFile.length());
                String extension = Files.getFileExtension(saveFile.getAbsolutePath());

                displayNewImageInformation(resolution, size, extension.toUpperCase());
            }

        });
    }

    private void updateResizeImageInformation(int changedWidthImage, int changedHeightImage) {
        FrameLayout.LayoutParams layoutParams = new FrameLayout.LayoutParams(FrameLayout.LayoutParams.WRAP_CONTENT, FrameLayout.LayoutParams.WRAP_CONTENT);
        layoutParams.gravity = Gravity.CENTER;
        selectedImageView.setLayoutParams(layoutParams);

        PicassoTarget picassoTarget = new PicassoTarget(this, fileUtility.getFilename(), selectedImageView);

        Picasso.get().load(fileUtility.getUploadedFile())
                .resize(changedWidthImage, changedHeightImage)
                .centerCrop(Gravity.CENTER)
                .into(picassoTarget);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == Activity.RESULT_OK) {

            hasDimensionChanged = 0;

            Uri uri = Objects.requireNonNull(data).getData();
            File helperFile = FileHelper.getFileFromIntentUri(ResizeImageActivity.this, data);

            String transferImagePath = uri.getPath();

            Picasso.get()
                    .load(helperFile)
                    .resize(400, 300)
                    .centerCrop()
                    .into(selectedImageView);

            //Process file
            fileUtility = new FileUtility(helperFile);
            String ext = Files.getFileExtension(helperFile.getAbsolutePath());

            setResizeData(fileUtility.getFileWidth(), fileUtility.getFileHeight(), ext.toUpperCase());

            onImageHeightResize();
            OnImageWidthResize();

            //Setup current file info
            displayImageInformation(fileUtility);

            //Set rows container visibility
            rowContainerVisibility.setVisibility(View.VISIBLE);

        } else if (resultCode == ImagePicker.RESULT_ERROR) {
            Toast.makeText(ResizeImageActivity.this, ImagePicker.getError(data), Toast.LENGTH_SHORT).show();
        } else {
            Toast.makeText(ResizeImageActivity.this, "Task Cancelled", Toast.LENGTH_SHORT).show();
        }
    }

    private void setDefaultFileExtension(String ext) {
        List<ThemedButton> buttons = themeGroup.getButtons();

        buttons.forEach(themedButton -> {
            if (themedButton.getText().equals(ext)) {
                themeGroup.selectButton(themedButton.getId());
            }
        });
    }

    private void setResizeData(String width, String height, String extension) {
        resizeWidth.setText(width);
        resizeHeight.setText(height);

        if (!extension.isEmpty()) {
            setDefaultFileExtension(extension);
        }
    }

    private void displayImageInformation(FileUtility fileUtility) {
        if (fileUtility != null) {
            currentImageResolution.setText(fileUtility.getFileResolution());
            currentImageSize.setText(fileUtility.getFileSize());
            currentImageExtension.setText(fileUtility.getExtension().toUpperCase());
        }
    }

    private void displayNewImageInformation(String resolution, String size, String extension) {
        newImageResolution.setText(resolution);
        newImageSize.setText(size);
        newImageExtension.setText(extension);
    }

    private void displayImageByPath(String path) {
        if (!Objects.equals(path, "")) {
            selectedImageView.setImageURI(Uri.fromFile(new File(path)));
        }
    }

    private void openGallery() {
        ImagePicker.with(this)
                .start();
    }

    private void saveImageResize() {
        String widthValue = Objects.requireNonNull(resizeWidth.getText()).toString();
        String heightValue = Objects.requireNonNull(resizeHeight.getText()).toString();

        if (widthValue.equals("") || heightValue.equals("")) {
            ToastUtils.showToast(ResizeImageActivity.this, "Width and Height values must be filled");
            return;
        }

        double widthNumeric = Double.parseDouble(widthValue);
        double heightNumeric = Double.parseDouble(heightValue);
    }


    private void saveImageBtn() {
        saveResizedImage.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if(isResizeByPercent) {
                    savResizeImageByPercent();
                } else {
                    saveResizeImageByPixel();
                }
            }
        });
    }

    public void savResizeImageByPercent(){

    }

    public void saveResizeImageByPixel(){

        Bitmap bitmap = ((BitmapDrawable) selectedImageView.getDrawable()).getBitmap();
        File file = getTempSaveFile(bitmap);
        String savedFilePath = file.getAbsolutePath();

        DialogUtils.showConfirmationDialog(this, "Image Resize successfully", "View Image - " + savedFilePath, "View Image",
                new AbstractDialog.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int which) {
                        dialogInterface.dismiss();
                        viewSavedImage(savedFilePath);
                    }
                }, "Cancel", new AbstractDialog.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int which) {
                        dialogInterface.dismiss();
                    }
                });

    }

    private void viewSavedImage(String path) {
        Intent saveInetnt = new Intent(ResizeImageActivity.this, ViewSavedImageActivity.class);
        saveInetnt.putExtra(ConstantUtils.IMAGE_VIEWER, path);
        startActivity(saveInetnt);
        Bungee.slideLeft(ResizeImageActivity.this);
    }

    private File getTempSaveFile(Bitmap bitmap) {

        //Get extension
        String selectedExtension = "jpg";

        List<ThemedButton> buttons = themeGroup.getButtons();
        for (ThemedButton button : buttons) {
            if (button.isSelected()) {
                selectedExtension = button.getSelectedText();
                selectedExtension = selectedExtension.toLowerCase();
            }
        }

        BitmapToFile bToFile = new BitmapToFile(ResizeImageActivity.this);
        bToFile.setExtension(selectedExtension);
        bToFile.setQuality(progressValue);

        return bToFile.getFileFromBitmap(bitmap, fileUtility.getFilename());
    }

    @Override
    public boolean onOptionsItemSelected(@NonNull MenuItem item) {
        int menuId = item.getItemId();
        if (menuId == android.R.id.home) {
            onBackPressed();
        }
        return super.onOptionsItemSelected(item);
    }


    @Override
    public void onBackPressed() {
        super.onBackPressed();
        Bungee.slideRight(this);
    }
}

ImageResizeHelper Class

We have abstracted some functions used for image resizing to keep the code clean.

Create a new folder named helpers. Inside this folder, create a new file named ImageRezizeHelper.Java.

Open the java file above, copy and paste the code below into the file.

public class ResizeImageHelper {

    private Context context;

    public ResizeImageHelper(Context context) {
        this.context = context;
    }

    public File resizeImageQuality(int quality, String extension, String filename, String storagePath, File originalImage){

        File resizedImage = null;

        String path = storagePath + "/" + filename + "." + extension;
        File file = new File(path);

        try {

            //Delete file if it exists
            if(file.exists()){
                file.delete();
            }

            resizedImage = new Resizer(this.context)
                    .setQuality(quality)
                    .setOutputFormat(extension)
                    .setOutputFilename(filename)
                    .setOutputDirPath(storagePath)
                    .setSourceImage(originalImage)
                    .getResizedFile();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

        return resizedImage;
    }
}

We end our tutorial on how to resize an image file in Android. This is part of the series on creating a new Android application from scratch.

If you missed something or have an issue or suggestion, kindly use our comment box to contact us.

The next feature in this series will focus on how to crop an image file in Android.

Leave a Reply