How to Resize Images Programmatically in Android?
Last Updated :
17 Sep, 2021
There are many applications available on the net for performing image operations such as cropping, reducing image file size, or resizing the images to particular dimensions. Most of these applications are API based where the image is uploaded to anonymous servers, various functions are performed and then displayed as a result available for download. The process becomes complex with the involvement of the internet. However, there are few applications that can locally perform similar operations.
Through this article, we will show you how you could resize an image to custom dimensions programmatically in Android.
Step by Step Implementation
Step 1: Create a New Project in Android Studio
To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. We demonstrated the application in Kotlin, so make sure you select Kotlin as the primary language while creating a New Project.
Step 2: Working with the activity_main.xml file
Navigate to the app > res > layout > activity_main.xml and add the below code to that file. Below is the code for the activity_main.xml file. Add two Buttons to upload and resize and an ImageView to display the image when uploaded and resized in the layout.
XML
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
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"
tools:context=".MainActivity">
<!-- Button to upload Image from the device -->
<Button
android:id="@+id/upload_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:text="Upload"/>
<!-- Button to perform resize operation -->
<Button
android:id="@+id/resize_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:text="Resize"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true" />
<!-- ImageView to display images after
uploading and resizing -->
<ImageView
android:id="@+id/imageView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"/>
</RelativeLayout>
Step 3: Working with the MainActivity.kt file
Go to the MainActivity.kt file and refer to the following code. Below is the code for the MainActivity.kt file. Comments are added inside the code to understand the code in more detail. Perform resizing operations in the main code.
Kotlin
import android.app.Activity
import android.content.Intent
import android.graphics.Bitmap
import android.graphics.ImageDecoder
import android.net.Uri
import android.os.Build
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.provider.MediaStore
import android.widget.Button
import android.widget.ImageView
import android.widget.Toast
import androidx.annotation.RequiresApi
import java.io.IOException
class MainActivity : AppCompatActivity() {
// Declaring ImageView, number of images to pick
// from the device and a Bitmap to store the image
private lateinit var mImageView: ImageView
private val mPickImage = 1
private lateinit var mYourBitmap: Bitmap
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
// Declaring and initializing the buttons
val mUploadButton = findViewById<Button>(R.id.upload_button)
val mResizeButton = findViewById<Button>(R.id.resize_button)
// Initializing the image view
mImageView = findViewById(R.id.imageView)
// When upload button is clicked, the intent navigates
// to the local content in the device,
// where one can select the desired image
mUploadButton.setOnClickListener {
val intent = Intent(Intent.ACTION_GET_CONTENT)
intent.type = "image/*"
startActivityForResult(intent, mPickImage)
}
// When resize button is clicked
mResizeButton.setOnClickListener {
// Generate a new Bitmap of custom dimensions and set it in the image view
val resized = Bitmap.createScaledBitmap(mYourBitmap, 300, 300, true)
mImageView.setImageBitmap(resized)
}
}
@RequiresApi(Build.VERSION_CODES.P)
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
if (requestCode == mPickImage && resultCode == Activity.RESULT_OK) {
// If the image file does not exist
if (data == null) {
Toast.makeText(applicationContext,"Error",Toast.LENGTH_SHORT).show()
return
}
// Otherwise
try {
// Load the image address and set it in the image view
val imageUri: Uri = data.data!!
val source = ImageDecoder.createSource(this.contentResolver, imageUri)
mYourBitmap = ImageDecoder.decodeBitmap(source)
mImageView.setImageBitmap(mYourBitmap)
} catch (e: IOException) {
e.printStackTrace()
}
}
}
}
Output:
You can see that the image size is reduced when resize button is clicked.
Similar Reads
How to Set an Image as Wallpaper Programmatically in Android? Setting wallpaper in Android programmatically is helpful when the application is fetching wallpapers from the API library and asking the user whether to set the wallpaper for the home screen or not. In this article, it's been discussed how to set a sample image as the home screen wallpaper programma
4 min read
How to Take Screenshot Programmatically in Android? In every android phone, we have feature to take screenshots of screens. In this article, we are going to explain how to take screenshots programmatically. Step-by-Step ImplementationStep 1: Create a New ProjectTo create a new project in Android Studio please refer to How to Create/Start a New Projec
4 min read
How to Change TextView Size Programmatically in Android? A TextView in Android is a UI element to display text. It can be programmed in the layout file statically as well as in the main code dynamically. Thus, various attributes of a TextView such as the text, text color, text size, TextView background, and its size can be changed programmatically. In thi
3 min read
How to Programmatically Take a Screenshot on Android? Ever wanted to take some perfect screenshot of a particular view, or perhaps some UI element ruined your favorite screenshot? Don't worry much, this Geeks for Geeks article will help you achieve it by making an app from scratch. As Below is the code for the title name in this article, we are going t
3 min read
How to Set Background Drawable Programmatically in Android? In many android applications, we can get to see that the background color of this application changes dynamically when updated from the server. For updating this color we have to set the background color of our layout programmatically. In this article, we will take a look at How to Set Background Dr
3 min read
How to Find Dots-Per-Inch (DPI) of Screen in Android Programmatically? Dots-Per-Inch or DPI is a measure of pixel density over the physical area on the screen. A pixel is the smallest unit of any screen display. and the sum of all the pixels present on the screen is termed as Screen Resolution. The pixels available to the user are called Viewport and in this article, w
2 min read
How to Lazy Load Images in Android ListView? Many times, the UI of an application gets blocked while downloading images from the internet. This problem can be solved by implementing lazy loading of images in the list view while displaying the text. It is a strategy to identify resources as unimportant and load them only when needed. It's a way
3 min read
How to Increase or Decrease TextView Font Size in Android Programmatically? In this App, we are going to learn how to increase or decrease TextView Font Size in Android programmatically. Like we have seen that in many apps we sometimes want to enlarge the text. So here basically we are going to implement that. A sample GIF is given below to get an idea about what we are goi
3 min read
How to Find the Screen Resolution of a Device Programmatically in Android? Screen Resolution refers to the number of pixels on display. A higher resolution means more pixels and more pixels provide the ability to display more visual information. This entity is widely used in applications related to the broadcasting of real-time visuals such as live video, gaming, etc for o
3 min read