Spring Boot: crop an uploaded image

In this previous post we described how to upload an image file in Spring Boot. What if we want to crop the image server side in order to always storeĀ a square image?

The following java method can be used in Spring Boot to crop an image in a square shape, centered in the image’s middle:

private BufferedImage cropImageSquare(byte[] image) throws IOException {
  // Get a BufferedImage object from a byte array
  InputStream in = new ByteArrayInputStream(image);
  BufferedImage originalImage = ImageIO.read(in);
  // Get image dimensions
  int height = originalImage.getHeight();
  int width = originalImage.getWidth();
  // The image is already a square
  if (height == width) {
    return originalImage;
  // Compute the size of the square
  int squareSize = (height > width ? width : height);
  // Coordinates of the image's middle
  int xc = width / 2;
  int yc = height / 2;
  // Crop
  BufferedImage croppedImage = originalImage.getSubimage(
      xc - (squareSize / 2), // x coordinate of the upper-left corner
      yc - (squareSize / 2), // y coordinate of the upper-left corner
      squareSize,            // widht
      squareSize             // height
  return croppedImage;

Usage example

Referring the code from this post, where the uploaded image is handled inside a controller as a MultipartFile object, named uploadfile, the following snippet of code crop the image before save it:

// Crop the image (uploadfile is an object of type MultipartFile)
BufferedImage croppedImage = cropImageSquare(uploadfile.getBytes());

// Get the file extension
String ext = FilenameUtils.getExtension(filename);

// Save the file locally
File outputfile = new File(filepath);
ImageIO.write(croppedImage, ext, outputfile);




Category BootstrapCategory CoffeescriptCategory DrupalCategory GravCategory HTMLCategory JavascriptCategory JoomlaCategory jQueryCategory LaravelCategory MagentoCategory PHPCategory SharePointCategory SpringCategory ThymeleafCategory WordPressCategory Workflow


Developed and designed by Netgloo
© 2019 Netgloo