Generating blank images of random size using Kotlin and Firebase Storage

Kacper Bąk
7 min readDec 18, 2022

--

Photo by Carson Masterson on Unsplash

Kotlin is a modern programming language that is concise, safe, and interoperable. It is widely used for Android development and its popularity is increasing in the development world. Moreover, it is backed by Google, which makes it an attractive language to learn.

You can generate a random URL with an image in Kotlin using the java.net.URL class.

First, create a new instance of the URL class passing in a valid URL string as an argument.

val url = URL("http://example.com/randomImage.png")

Next, use the openStream() method to open a connection to the URL and retrieve the image data as an InputStream.

val imageStream = url.openStream()

Finally, you can use the InputStream to create a Bitmap object and display the image in your UI.

val bitmap = BitmapFactory.decodeStream(imageStream)
imageView.setImageBitmap(bitmap)

You can save a data class in Kotlin to include an image by using the following steps:

Create a data class with a property for the image. For example:

data class MyDataClass(val image: Bitmap)

Add the necessary code to read the image from a file or URL and convert it to a Bitmap object. Store the Bitmap object in the data class instance. Serialize the data class instance using a library such as Gson, Jackson, or kryo. This will convert the data class instance into a JSON or other format that can be saved to a file.Save the file containing the serialized data class instance to a location of your choosing, such as a local file system or cloud storage.

I integrated the whole thing into Firebase in my application. To search for an image using Firebase, you must first log into Firebase Console. After logging in, go to the ‘Storage’ tab. In this tab, you can browse the files stored in Firebase Storage. You can search for them using a filter and keywords that are related to the image you are looking for. Once you have found the image, you can view, download or delete it.

As a rule the images should be saved in the application’s internal storage. This will ensure that the images are secure and only accessible by the application. They can also be saved in the application’s external storage, but this is less secure since it can be accessed by other applications.

However, in the case of my particular application images should be stored in dedicated cloud storage such as Amazon S3 or Firebase Storage, in order to be shared with other users. This will ensure that the images are available to all users who are using the app, and that the images can be accessed quickly and reliably.

You can save an image to Firebase Storage using Kotlin by using the StorageReference.putFile() method. This method takes a Uri argument which is the URI of the file that you want to upload. Once the file is uploaded, the StorageReference.putFile() method will return a Task that you can use to monitor progress and determine when the upload is complete.

To initialize a Storage Reference, you can use the getReference() method on an instance of FirebaseStorage. For example:

FirebaseStorage storage = FirebaseStorage.getInstance();
StorageReference storageRef = storage.getReference();

The button responsible for adding an image to Firebase Storage should be labeled “Upload Image” or “Add Image” depending on the context.

A product model should include a detailed description of the product, its features, and specifications, as well as a clear picture of the product. The picture should be high-quality, and should accurately show the product in its entirety, including any components or sub-components. Additionally, the product model should include information about the product’s price, any warranties or guarantees offered, and any available customization options.

Creating a bitmap in Kotlin code is relatively simple. The following code snippet shows how to create a new bitmap with a width and height of 200 pixels:

        private fun createBitmap(): Bitmap {
return Bitmap.createBitmap(200, 300, Bitmap.Config.ARGB_8888)
}

PutBytes can be used in Kotlin when you need to write binary data to a file. It is useful for writing images, audio files, or other binary data. It is faster than using the standard FileWriter, and it can also be used to overwrite existing files.

...
// add image to firebase
val data = baos.toByteArray()
val storageRef = Firebase.database.getReference("images")
val imageRef = storageRef.child(it.name)
val uploadTask = imageRef.putBytes(data)
uploadTask.addOnFailureListener {
Log.e("uploadImage", "Image upload failed")
Log.e("uploadImage", it.message!!)
}.addOnSuccessListener {
Log.d("uploadImage", "Image uploaded succesfully")
}
}
}
return null
}
}

The PutBytes function is part of the Amazon S3 Transfer Manager, a library designed to make it easier to upload and download files from Amazon S3. The library is available for download from the Amazon AWS website.

PutBytes is a method of the Firebase Storage class, part of the Firebase Storage SDK for Android. To use it, you need to include the Firebase Storage dependency in your project.

You can access the PutBytes method using the Firebase Storage API in Kotlin like so:

// Create a reference to the file to upload
val storageRef = FirebaseStorage.getInstance().getReference("myfile.jpg")

// Create a File object for the file to upload
val file = File("myImage.jpg")

// Get the data from the file
val fileData = file.readBytes()

// Upload the file to Firebase Storage
storageRef.putBytes(fileData)
.addOnSuccessListener {
// File uploaded successfully
}
.addOnFailureListener {
// Handle unsuccessful uploads
}

Firebase Storage is a cloud storage solution for storing user-generated content like images, audio, and video. It is built for app developers who need to store and serve user-generated content, such as photos or videos. Firebase Storage provides secure file uploads and downloads for Firebase apps, regardless of network quality. It is backed by Google Cloud Storage, a powerful, simple, and cost-effective object storage service.

Create a class called FirebaseStorageService and import FirebaseStorage.

Create a property for FirebaseStorage.

class FirebaseStorageService {
private val firebaseStorage: FirebaseStorage = FirebaseStorage.getInstance()

fun upload(image: ByteArray, filename: String): Task<Uri> {
val fileRef = firebaseStorage.reference.child(filename)
return fileRef.putBytes(image).continueWithTask {
fileRef.downloadUrl
}
}
}

Extract to separate file class FirebaseStorage


class FirebaseStorage {
private val firebaseStorage: FirebaseStorage = FirebaseStorage.getInstance()

fun upload(image: ByteArray, filename: String): Task<Uri> {
val fileRef = firebaseStorage.reference.child(filename)
return fileRef.putBytes(image).continueWithTask {
fileRef.downloadUrl
}
}
}

This code declares a private val (a read-only variable) named firebaseStorage, which is an instance of FirebaseStorage. FirebaseStorage is a class provided by Firebase that allows you to store files in the cloud. The code retrieves an instance of FirebaseStorage using the static getInstance() method.

The getInstance() method is a static method of the FirebaseStorage class. You do not need to import it separately; it is available when you import the FirebaseStorage class.

Simplifying, the whole class could look like this:

class FirebaseStorageService {

companion object {
private var instance: FirebaseStorageService? = null

fun getInstance(): FirebaseStorageService {
if (instance == null) {
instance = FirebaseStorageService()
}
return instance!!
}
}

fun getReference(path: String): StorageReference {
return FirebaseStorage.getInstance().getReference(path)
}

fun getReferenceFromUrl(url: String): StorageReference {
return FirebaseStorage.getInstance().getReferenceFromUrl(url)
}

}

You do not need to create a class yourself to create the Singleton responsible for handling Firebase Storage. You can use an import and a library already created for this purpose. I believe that this approach, can save a lot of work.

If we do this, we can save a great deal of space, and the target code responsible for adding the image can look like this.

                val storage = FirebaseStorageService.getInstance()
val storageRef = storage.getReference("images/${it.name}.jpg")
storageRef.putBytes(baos.toByteArray())
.addOnSuccessListener {
Log.d("FirebaseStorage", "Image uploaded successfully")
}
.addOnFailureListener {
Log.d("FirebaseStorage", "Image upload failed")
}

Of course, if you have not configured Firebase Storage properly, you should get a message like this from the console.

     Caused by: java.io.IOException: {  "error": {    "code": 403,    "message": "Permission denied."  }}

Firebase Storage permission checks cannot be turned off and must be enabled in order to use the service. Without these checks, any user would be able to access and modify any files stored in the storage bucket, which would be a major security risk.

The first step is to create a service account for yourself in the Firebase Console. Once you have the service account, you can assign permission to it using the IAM & Admin page in the Firebase Console. From there, you can select the service account you created, and then select the roles you wish to assign to it (such as Storage Object Viewer). Once you have saved your changes, you should be able to test whether Firebase Storage is working as expected.

Images that have been created using only code

Below is a link to the entire project, from which I extracted pieces of code that evolved during the writing of the article.

https://github.com/53jk1/ExchangeableToken

Summary

This article explains how to generate random images with Kotlin. It begins by discussing the concept of randomness and how it can be applied to images. It then covers the basics of Kotlin programming and how to use it to generate random images. This includes topics such as creating a canvas, drawing shapes, and adding colors. Finally, the article provides code samples and examples of random images generated using Kotlin. This article is a great resource for anyone interested in learning how to generate random images using Kotlin.

--

--