SATURN  RING  STATION

At a distant space view post, we chat about codes.

Java(2D Graphics API) large image splits into chunks of squares and then rejoin back to original.

There are some examples online that split image into set number of chunks (e.g. 3×3, 5×4). Be careful that some of them, in order to get a evenly divided images, may sacrifice the remainder pixels. However, the one I gonna share is splitting large image into a fixed size square chunks of images keeping the remainders as smaller chunks of images, then rejoin them back to the original. Cropping into squares is simple, handling remainders need a little bit extra care.

Have a look at a map to see what remainders I’m talking about.

 

Let say the map is the image, grid lines are the squares we gonna crop. You can see remainders(not perfect squares) in both most right column and bottom row of the image.

The logic is:

 

  • Do regular squares cropping.
  • if (width / lenght of square has a remainder) we have right column sub rectangle chunks.
  • if (width / lenght of square has a remainder) we have bottom row sub rectangle chunks.
  • if (both have remainders) we have an extra little chunk at the very end of right and bottom(rectangle starting at 26  x 43 on map).

 

In this case, we crop them into squares with 500 x 500 pixels each.

 

 

Take a look at the image chunks output name. For rejoining image chunks back to the original in correct order, I marked down its column number, total columns count, row number and total rows count.

Here is the rejoin code.

 

 

I’m using addition instead of multiplication for setting width and height in drawImage method because of the remainders’ width and height irregularity. Also, it’s a little bit faster.

You can tell from the code that square size can be easily changes, and it’s not limiting into cropping squares. We can do rectangle too, just be careful changing the values in Graphics2D API.

Leave a Comment

Your email address will not be published. Required fields are marked *

Java(2D Graphics API) large image splits into chunks of squares and then rejoin back to original.