Skip to content

Commit

Permalink
Update image save workflow
Browse files Browse the repository at this point in the history
* throw new checked exception if format not found
* add `saveAsPng` method
  • Loading branch information
AntonOellerer committed Nov 7, 2024
1 parent 15fbcc0 commit 7d8c75e
Show file tree
Hide file tree
Showing 4 changed files with 26 additions and 8 deletions.
2 changes: 1 addition & 1 deletion build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ plugins {
}

group 'com.docutools'
version = '4.2.8'
version = '5.0.0'

java {
toolchain {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -40,19 +40,28 @@ public BufferedImage getImage() {
}

@Override
public Path saveAsJpeg() throws IOException {
public Path saveAsJpeg() throws IOException, NoWriterFoundException {
return saveAs(".jpg", "JPEG");
}

@Override
public Path saveAsPng() throws IOException, NoWriterFoundException {
return saveAs(".png", "PNG");
}

private Path saveAs(String suffix, String formatName) throws IOException, NoWriterFoundException {
if (image == null) {
throw new ImageReferenceClosedException("Image was already closed.");
}

var filePath = Files.createTempFile("jocument-", ".jpg");
var filePath = Files.createTempFile("jocument-", suffix);
log.trace("Saving image {} to '{}'...", id, filePath);

boolean foundWriter = ImageIO.write(image, "JPEG", filePath.toFile());
boolean foundWriter = ImageIO.write(image, formatName, filePath.toFile());
if (!foundWriter) {
throw new IOException("Found no JPG writer");
throw new NoWriterFoundException(formatName);
}
log.trace("Successfully saved image {} to '{}'!", id, filePath);
log.trace("Successfully saved image {} to '{}'", id, filePath);

return filePath;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ public abstract class ImageReference implements AutoCloseable {
* @param width width in pixel
* @param height height in pixel
*/
public ImageReference(int width, int height) {
protected ImageReference(int width, int height) {
this.id = UUID.randomUUID();
this.width = width;
this.height = height;
Expand Down Expand Up @@ -62,7 +62,9 @@ public int getHeight() {
*
* @return the {@link Path} to the JPEG
*/
public abstract Path saveAsJpeg() throws IOException;
public abstract Path saveAsJpeg() throws IOException, NoWriterFoundException;

public abstract Path saveAsPng() throws IOException, NoWriterFoundException;

@Override
public abstract void close();
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
package com.docutools.jocument.image;

public class NoWriterFoundException extends Exception {
public NoWriterFoundException(String type) {
super("Found no writer for type %s".formatted(type));
}
}

0 comments on commit 7d8c75e

Please sign in to comment.