AbracaDabra
AbracaDabra

Reputation: 41

How to break an image to subimages?

What is the shortest code one can write in java to break an image (say 200x1000) into 10 images of a tenth height but same width (200x 100)?

Mine is a pretty long code; the main part , I am just giving:

for (int i_=0;i_<10;i_++)
            {
                for(int k=i_*100;k<i_*100+h/10;k++)
                    {
                        for(int j_=0;j_<w;j_++)
                            {
        
                                int pixv=img.getRGB(j_,k);
                                r=(pixv>>16)&0xff;
                                g=(pixv>>8)&0xff;
                                b=(pixv)&0xff;
                                int rgb=new Color(r,g,b).getRGB();
                                img.setRGB(j_,k-i_*200,rgb);
                             }
                     }
                 // Here I am writing the img to a new .bmp file thus creating 10 seperate files
             }

Here img is a BufferedImage

w,h the width and height of large image

Upvotes: 2

Views: 279

Answers (1)

Eritrean
Eritrean

Reputation: 16498

you can get a sub image from BufferedImage using getSubimage(int x,int y,int w,int h). Try this:

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;

public class NewClass9 {

public static void main(String[] args) throws IOException{
  BufferedImage img = null;
  img = ImageIO.read(new File("C:\\users\\uzochi\\desktop\\Penguins.jpg"));
  for(int i = 0;i<10;i++){
    BufferedImage sub = img.getSubimage(0, i*(img.getHeight()/10), img.getWidth(), img.getHeight()/10);
    File f = new File("C:\\users\\uzochi\\desktop\\SubImage"+i+".png");
    ImageIO.write(sub, "png", f);
  }
}

}

Upvotes: 1

Related Questions