Skip to content

Commit

Permalink
Update README.md
Browse files Browse the repository at this point in the history
  • Loading branch information
sigpwned authored Feb 27, 2024
1 parent cdbb6fc commit e7d9c0f
Showing 1 changed file with 9 additions and 38 deletions.
47 changes: 9 additions & 38 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
# smartcrop4j

Content-aware image cropping for Java based on the excellent [@jwagner/smartcrop.js](https://github.com/jwagner/smartcrop.js).
Content-aware image cropping for Java 11+ based on the excellent [@jwagner/smartcrop.js](https://github.com/jwagner/smartcrop.js).

## Functionality

Expand All @@ -16,45 +16,16 @@ Given a `BufferedImage`, `smartcrop4j` considers the following heuristics to rec

## Quickstart

To crop a loaded image, simply use:
To produce a crop of an image of a given width and height with the default configuration, simply use:

public BufferedImage crop(BufferedImage originalImage) {
public BufferedImage crop(BufferedImage originalImage, int cropWidth, int cropHeight) {
return Smartcrop.crop(originalImage, width, height);
}

To load an image from a file, crop it, and store the result in a new file with the same image type, use:

public File crop(File originalImageFile) throws IOException {
String imageFileExtension=Optional.ofNullable(originalImageFile.getName())
.filter(f -> f.contains("."))
.map(f -> f.substring(f.lastIndexOf(".") + 1))
.orElseThrow(() -> new IllegalArgumentException("File must have extension"));

BufferedImage originalImage;
ImageInputStream input = ImageIO.createImageInputStream(originalImageFile);
if(input == null)
throw new IllegalArgumentException("File extension "+imageFileExtension+" is not a recognized file format");
try (input) {
originalImage = ImageIO.read(input);
}

BufferedImage croppedImage=Smartcrop.crop(originalImage, width, height);

File result = null;
File croppedImageFile=File.createTempFile("cropped.", "."+imageFileExtension);
try {
ImageOutputStream output=ImageIO.createImageOutputStream(croppedImageFile);
if(output == null)
throw new IOException("Failed to write file format "+imageFileExtension);
try (output) {
ImageIO.write(output, croppedImage);
}
result = croppedImageFile;
}
finally {
if(result == null)
croppedImageFile.delete();
}

return result;
This will cause the system to choose a crop of the appropriate aspect ratio and then copy the result to a new image, possibly scaling the cropped area up or down depending on the image and crop sizes.

To load an image from a file, crop it, and store the result in a new file with the same image type, all using the default configuration, use:

public File crop(File imageFile, int cropWidth, int cropHeight) throws IOException {
Smartcrop.crop(imageFile, cropWidth, cropHeight);
}

0 comments on commit e7d9c0f

Please sign in to comment.