A certain project required a large amount of heavy png
image samples.
On the other hand, when the image was generated in the form of simply fill
ing the square, it was compressed and became about several KB at most, so the capacity could not be secured.
Since the required image format was also decided, it was difficult to simply increase the area and gain capacity.
Compression usually works strongly when the following two points are true.
--The same pattern continues --The same color continues
Therefore, I did it with the glue that "If you draw a lot of random lines of random colors, it will be difficult to compress."
The target is a size of 1940 x 500 and 2MB per sheet. As long as we have achieved that, we will do it without worrying about further increase in capacity and processing time.
This is a sample to generate 2000 images in the $ {project root} / build / generated
directory.
If there are 100000 lines
, it will stably exceed 2MB.
parallelStream ()
is about "It will be a little faster", and I have not confirmed whether it is actually faster.
import java.awt.Color
import java.awt.Graphics2D
import java.awt.image.BufferedImage
import java.io.File
import javax.imageio.ImageIO
import kotlin.random.Random
const val width = 1940
const val height = 500
const val lines = 100000 //Number of lines
const val count = 2000
fun main() {
val generateTarget = System.getProperty("user.dir") + "/build/generated/"
List(count) { it }.parallelStream().forEach { index ->
val img = BufferedImage(width, height, BufferedImage.TYPE_3BYTE_BGR)
(img.graphics as Graphics2D).apply {
repeat(lines) {
//The transparency is also specified with the aim of increasing the capacity of the color as much as possible.
this.color = Random.nextBytes(4).let {
Color(it[0] + 128, it[1] + 128, it[2] + 128, it[3] + 128)
}
this.drawLine(Random.nextInt(width), Random.nextInt(height), Random.nextInt(width), Random.nextInt(height))
}
dispose()
}
ImageIO.write(img, "png", File("$generateTarget${index}.png "))
}
}
It was 4.81GB with 2000 sheets and 2.4MB on average. The load is high and the execution time is reasonable, so I think it's best to turn it around in your spare time.
An image like this will be generated.
Recommended Posts