Add Java Image process

This commit is contained in:
YuCheng Hu 2023-09-03 10:31:46 -04:00 committed by honeymoose
parent a68493c2ec
commit c9f430ae03
44 changed files with 25682 additions and 216 deletions

View File

@ -21,23 +21,21 @@
<module name="core-java-collections-list" />
<module name="spring-data-jpa-repo-2" />
<module name="core-java-streams" />
<module name="core-java-io-2" />
<module name="core-java-io" />
<module name="core-java-8-2" />
<module name="discourse" />
<module name="image-processing" />
<module name="spring-data-redis" />
<module name="core-java" />
<module name="core-java-collections-list-2" />
<module name="core-java-collections-list-3" />
<module name="core-java-collections-conversions-2" />
<module name="core-java-collections-list-3" />
<module name="core-java-8" />
<module name="core-java-collections-3" />
<module name="core-java-collections-2" />
</profile>
</annotationProcessing>
<bytecodeTargetLevel>
<module name="java-collections-conversions" target="11" />
<module name="java-collections-conversions-2" target="11" />
</bytecodeTargetLevel>
</component>
<component name="JavacSettings">
<option name="ADDITIONAL_OPTIONS_OVERRIDE">

View File

@ -27,6 +27,8 @@
<file url="file://$PROJECT_DIR$/core-java-modules/core-java-collections/src/main/resources" charset="UTF-8" />
<file url="file://$PROJECT_DIR$/core-java-modules/core-java-datetime-conversion/src/main/java" charset="UTF-8" />
<file url="file://$PROJECT_DIR$/core-java-modules/core-java-datetime-conversion/src/main/resources" charset="UTF-8" />
<file url="file://$PROJECT_DIR$/core-java-modules/core-java-io-2/src/main/java" charset="UTF-8" />
<file url="file://$PROJECT_DIR$/core-java-modules/core-java-io-2/src/main/resources" charset="UTF-8" />
<file url="file://$PROJECT_DIR$/core-java-modules/core-java-io/src/main/java" charset="UTF-8" />
<file url="file://$PROJECT_DIR$/core-java-modules/core-java-io/src/main/resources" charset="UTF-8" />
<file url="file://$PROJECT_DIR$/core-java-modules/core-java-numbers/src/main/java" charset="UTF-8" />
@ -39,8 +41,8 @@
<file url="file://$PROJECT_DIR$/core-java-modules/core-java/src/main/resources" charset="UTF-8" />
<file url="file://$PROJECT_DIR$/core-java-modules/src/main/java" charset="UTF-8" />
<file url="file://$PROJECT_DIR$/core-java-modules/src/main/resources" charset="UTF-8" />
<file url="file://$PROJECT_DIR$/java-collections-conversions/src/main/java" charset="UTF-8" />
<file url="file://$PROJECT_DIR$/java-collections-conversions/src/main/resources" charset="UTF-8" />
<file url="file://$PROJECT_DIR$/image-processing/src/main/java" charset="UTF-8" />
<file url="file://$PROJECT_DIR$/image-processing/src/main/resources" charset="UTF-8" />
<file url="file://$PROJECT_DIR$/persistence-modules/activejdbc/src/main/java" charset="UTF-8" />
<file url="file://$PROJECT_DIR$/persistence-modules/activejdbc/src/main/resources" charset="UTF-8" />
<file url="file://$PROJECT_DIR$/persistence-modules/spring-data-jpa-repo-2/src/main/java" charset="UTF-8" />

View File

@ -2,9 +2,12 @@ package com.ossez.java.lists;
import java.util.Arrays;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
import org.apache.commons.lang3.builder.ReflectionToStringBuilder;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.builder.ToStringBuilder;
import org.junit.Test;
public class ListToStringUnitTest {
@ -27,5 +30,28 @@ public class ListToStringUnitTest {
public void whenStringUtilsJoin_thenPrintCustom() {
List<Integer> intList = Arrays.asList(1, 2, 3);
System.out.println(StringUtils.join(intList, "|"));
// Object obj1 = new Integer(100);
// System.out.println(obj1.toString());
// ToStringBuilder.reflectionToString(intList);
Country country = new Country("United States", "North America", 4000000);
System.out.println(ReflectionToStringBuilder.toString(intList));
}
class Country {
private String name;
private String continent;
private int population;
public Country(String name, String continent, int population) {
this.name = name;
this.continent = continent;
this.population = population;
}
}
}

View File

@ -29,7 +29,7 @@
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>${version.log4j}</version>
<version>${log4j.version}</version>
</dependency>
<!-- test scoped -->
<dependency>

View File

@ -71,7 +71,7 @@
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>${version.log4j}</version>
<version>${log4j.version}</version>
</dependency>
<dependency> <!-- needed to bridge to slf4j for projects that use the log4j APIs directly -->
<groupId>org.slf4j</groupId>

View File

@ -35,7 +35,7 @@
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>${version.log4j}</version>
<version>${log4j.version}</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>

View File

@ -0,0 +1,11 @@
## Image Processing
This module contains articles about image processing.
### Relevant Articles:
- [Working with Images in Java](https://www.baeldung.com/java-images)
- [Intro to OpenCV with Java](https://www.baeldung.com/java-opencv)
- [Optical Character Recognition with Tesseract](https://www.baeldung.com/java-ocr-tesseract)
- [How Can I Resize an Image Using Java?](https://www.baeldung.com/java-resize-image)
- [Adding Text to an Image in Java](https://www.baeldung.com/java-add-text-to-image)
- [Capturing Image From Webcam in Java](https://www.baeldung.com/java-capture-image-from-webcam)

116
image-processing/pom.xml Normal file
View File

@ -0,0 +1,116 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<artifactId>image-processing</artifactId>
<name>image-processing</name>
<parent>
<groupId>com.ossez</groupId>
<artifactId>parent-modules</artifactId>
<version>0.0.2-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath>
</parent>
<dependencies>
<dependency>
<groupId>net.imagej</groupId>
<artifactId>ij</artifactId>
<version>${ij.version}</version>
<exclusions>
<exclusion>
<artifactId>commons-logging</artifactId>
<groupId>commons-logging</groupId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.openimaj</groupId>
<artifactId>core-image</artifactId>
<version>${core-image.version}</version>
<exclusions>
<exclusion>
<artifactId>commons-logging</artifactId>
<groupId>commons-logging</groupId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.openpnp</groupId>
<artifactId>opencv</artifactId>
<version>${opencv.version}</version>
</dependency>
<dependency>
<groupId>com.twelvemonkeys.imageio</groupId>
<artifactId>imageio-core</artifactId>
<version>${imageio.version}</version>
</dependency>
<dependency>
<groupId>com.twelvemonkeys.imageio</groupId>
<artifactId>imageio-bmp</artifactId>
<version>${imageio.version}</version>
</dependency>
<dependency>
<groupId>net.sourceforge.tess4j</groupId>
<artifactId>tess4j</artifactId>
<version>${tess4j.version}</version>
</dependency>
<dependency>
<groupId>org.bytedeco</groupId>
<artifactId>tesseract-platform</artifactId>
<version>${tesseract-platform.version}</version>
</dependency>
<dependency>
<groupId>org.imgscalr</groupId>
<artifactId>imgscalr-lib</artifactId>
<version>${imgscalr-version}</version>
</dependency>
<dependency>
<groupId>net.coobird</groupId>
<artifactId>thumbnailator</artifactId>
<version>${thumbnailator-version}</version>
</dependency>
<dependency>
<groupId>com.github.downgoon</groupId>
<artifactId>marvin</artifactId>
<version>${marvin-version}</version>
<type>pom</type>
</dependency>
<dependency>
<groupId>com.github.downgoon</groupId>
<artifactId>MarvinPlugins</artifactId>
<version>${marvin-version}</version>
</dependency>
<dependency>
<groupId>org.bytedeco</groupId>
<artifactId>javacv-platform</artifactId>
<version>${javacv-platform.version}</version>
</dependency>
<dependency>
<groupId>com.github.sarxos</groupId>
<artifactId>webcam-capture</artifactId>
<version>${webcam-capture.version}</version>
</dependency>
<dependency>
<groupId>org.openjfx</groupId>
<artifactId>javafx-graphics</artifactId>
<version>${javafx-graphics.version}</version>
</dependency>
</dependencies>
<properties>
<core-image.version>1.3.10</core-image.version>
<ij.version>1.51h</ij.version>
<imageio.version>3.3.2</imageio.version>
<tess4j.version>4.5.1</tess4j.version>
<tesseract-platform.version>4.1.0-1.5.2</tesseract-platform.version>
<opencv.version>4.7.0-0</opencv.version>
<javacv-platform.version>1.5.5</javacv-platform.version>
<webcam-capture.version>0.3.12</webcam-capture.version>
<imgscalr-version>4.2</imgscalr-version>
<thumbnailator-version>0.4.11</thumbnailator-version>
<marvin-version>1.5.5</marvin-version>
<javafx-graphics.version>11</javafx-graphics.version>
</properties>
</project>

View File

@ -0,0 +1,25 @@
package com.baeldung.image.resize.core;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
public class Graphics2DExample {
static BufferedImage resizeImage(BufferedImage originalImage, int targetWidth, int targetHeight) {
BufferedImage resizedImage = new BufferedImage(targetWidth, targetHeight, BufferedImage.TYPE_INT_RGB);
Graphics2D graphics2D = resizedImage.createGraphics();
graphics2D.drawImage(originalImage, 0, 0, targetWidth, targetHeight, null);
graphics2D.dispose();
return resizedImage;
}
public static void main(String[] args) throws IOException {
BufferedImage originalImage = ImageIO.read(new File("src/main/resources/images/sampleImage.jpg"));
BufferedImage outputImage = resizeImage(originalImage, 200, 200);
ImageIO.write(outputImage, "jpg", new File("src/main/resources/images/sampleImage-resized-graphics2d.jpg"));
}
}

View File

@ -0,0 +1,24 @@
package com.baeldung.image.resize.core;
import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
public class ImageScaledInstanceExample {
static BufferedImage resizeImage(BufferedImage originalImage, int targetWidth, int targetHeight) {
Image resultingImage = originalImage.getScaledInstance(targetWidth, targetHeight, Image.SCALE_DEFAULT);
BufferedImage bufferedImage = new BufferedImage(targetWidth, targetHeight, BufferedImage.TYPE_INT_RGB);
bufferedImage.getGraphics()
.drawImage(resultingImage, 0, 0, null);
return bufferedImage;
}
public static void main(String[] args) throws IOException {
BufferedImage originalImage = ImageIO.read(new File("src/main/resources/images/sampleImage.jpg"));
BufferedImage outputImage = resizeImage(originalImage, 200, 200);
ImageIO.write(outputImage, "jpg", new File("src/main/resources/images/sampleImage-resized-scaledinstance.jpg"));
}
}

View File

@ -0,0 +1,24 @@
package com.baeldung.image.resize.imgscalr;
import java.awt.image.BufferedImage;
import java.io.File;
import javax.imageio.ImageIO;
import org.imgscalr.Scalr;
public class ImgscalrExample {
public static BufferedImage simpleResizeImage(BufferedImage originalImage, int targetWidth) {
return Scalr.resize(originalImage, targetWidth);
}
public static BufferedImage resizeImage(BufferedImage originalImage, int targetWidth, int targetHeight) {
return Scalr.resize(originalImage, Scalr.Method.AUTOMATIC, Scalr.Mode.AUTOMATIC, targetWidth, targetHeight, Scalr.OP_ANTIALIAS);
}
public static void main(String[] args) throws Exception {
BufferedImage originalImage = ImageIO.read(new File("src/main/resources/images/sampleImage.jpg"));
BufferedImage outputImage = resizeImage(originalImage, 200, 200);
ImageIO.write(outputImage, "jpg", new File("src/main/resources/images/sampleImage-resized-imgscalr.jpg"));
}
}

View File

@ -0,0 +1,29 @@
package com.baeldung.image.resize.marvin;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import org.marvinproject.image.transform.scale.Scale;
import marvin.image.MarvinImage;
public class MarvinExample {
static BufferedImage resizeImage(BufferedImage originalImage, int targetWidth, int targetHeight) {
MarvinImage image = new MarvinImage(originalImage);
Scale scale = new Scale();
scale.load();
scale.setAttribute("newWidth", targetWidth);
scale.setAttribute("newHeight", targetHeight);
scale.process(image.clone(), image, null, null, false);
return image.getBufferedImageNoAlpha();
}
public static void main(String args[]) throws IOException {
BufferedImage originalImage = ImageIO.read(new File("src/main/resources/images/sampleImage.jpg"));
BufferedImage outputImage = resizeImage(originalImage, 200, 200);
ImageIO.write(outputImage, "jpg", new File("src/main/resources/images/sampleImage-resized-marvin.jpg"));
}
}

View File

@ -0,0 +1,31 @@
package com.baeldung.image.resize.thumbnailator;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import net.coobird.thumbnailator.Thumbnails;
public class ThumbnailatorExample {
static BufferedImage resizeImage(BufferedImage originalImage, int targetWidth, int targetHeight) throws IOException {
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
Thumbnails.of(originalImage)
.size(targetWidth, targetHeight)
.outputFormat("JPEG")
.outputQuality(0.90)
.toOutputStream(outputStream);
byte[] data = outputStream.toByteArray();
ByteArrayInputStream inputStream = new ByteArrayInputStream(data);
return ImageIO.read(inputStream);
}
public static void main(String[] args) throws Exception {
BufferedImage originalImage = ImageIO.read(new File("src/main/resources/images/sampleImage.jpg"));
BufferedImage outputImage = resizeImage(originalImage, 200, 200);
ImageIO.write(outputImage, "jpg", new File("src/main/resources/images/sampleImage-resized-thumbnailator.jpg"));
}
}

View File

@ -0,0 +1,31 @@
package com.baeldung.imagefromwebcam;
import marvin.gui.MarvinImagePanel;
import marvin.image.MarvinImage;
import marvin.io.MarvinImageIO;
import marvin.video.MarvinJavaCVAdapter;
import marvin.video.MarvinVideoInterface;
import marvin.video.MarvinVideoInterfaceException;
public class MarvinExample {
public static void main(String[] args) throws MarvinVideoInterfaceException {
MarvinVideoInterface videoAdapter = new MarvinJavaCVAdapter();
videoAdapter.connect(0);
MarvinImage image = videoAdapter.getFrame();
MarvinImageIO.saveImage(image, "selfie.jpg");
}
public void captureWithPanel() throws MarvinVideoInterfaceException {
MarvinVideoInterface videoAdapter = new MarvinJavaCVAdapter();
videoAdapter.connect(0);
MarvinImage image = videoAdapter.getFrame();
MarvinImagePanel imagePanel = new MarvinImagePanel();
imagePanel.setImage(image);
imagePanel.setSize(800,600);
imagePanel.setVisible(true);
}
}

View File

@ -0,0 +1,31 @@
package com.baeldung.imagefromwebcam;
import org.bytedeco.javacv.*;
import org.bytedeco.opencv.opencv_core.IplImage;
import java.awt.event.WindowEvent;
import javax.swing.JFrame;
import static org.bytedeco.opencv.helper.opencv_imgcodecs.cvSaveImage;
public class OpenCVExample {
public static void main(String[] args) throws Exception {
CanvasFrame canvas = new CanvasFrame("Web Cam");
canvas.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
FrameGrabber grabber = new OpenCVFrameGrabber(0);
OpenCVFrameConverter.ToIplImage converter = new OpenCVFrameConverter.ToIplImage();
grabber.start();
Frame frame = grabber.grab();
IplImage img = converter.convert(frame);
cvSaveImage("selfie.jpg", img);
canvas.showImage(frame);
Thread.sleep(2000);
canvas.dispatchEvent(new WindowEvent(canvas, WindowEvent.WINDOW_CLOSING));
}
}

View File

@ -0,0 +1,41 @@
package com.baeldung.imagefromwebcam;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.JFrame;
import com.github.sarxos.webcam.Webcam;
import com.github.sarxos.webcam.WebcamPanel;
import com.github.sarxos.webcam.WebcamResolution;
import com.github.sarxos.webcam.util.ImageUtils;
public class WebcamCaptureExample {
public static void main(String[] args) throws IOException, Exception {
Webcam webcam = Webcam.getDefault();
webcam.open();
BufferedImage image = webcam.getImage();
ImageIO.write(image, ImageUtils.FORMAT_JPG, new File("selfie.jpg"));
}
public void captureWithPanel() {
Webcam webcam = Webcam.getDefault();
webcam.setViewSize(WebcamResolution.VGA.getSize());
WebcamPanel panel = new WebcamPanel(webcam);
panel.setImageSizeDisplayed(true);
JFrame window = new JFrame("Webcam");
window.add(panel);
window.setResizable(true);
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
window.pack();
window.setVisible(true);
}
}

View File

@ -0,0 +1,219 @@
package com.baeldung.imageprocessing.addingtext;
import ij.IJ;
import ij.ImagePlus;
import ij.process.ImageProcessor;
import java.awt.*;
import java.awt.font.GlyphVector;
import java.awt.font.TextAttribute;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.text.AttributedString;
import javax.imageio.ImageIO;
public class AddText {
public static void main(String[] args) throws IOException {
String imagePath = AddText.class.getClassLoader().getResource("lena.jpg").getPath();
ImagePlus resultPlus = signImageImageProcessor("www.baeldung.com", imagePath);
resultPlus.show();
ImagePlus resultGraphics = new ImagePlus("", signImageGraphics("www.baeldung.com", imagePath));
resultGraphics.show();
ImagePlus resultGraphicsWithIterator = new ImagePlus("", signImageGraphicsWithIterator("www.baeldung.com", imagePath));
resultGraphicsWithIterator.show();
ImagePlus resultGraphicsCentered = new ImagePlus("", signImageCenter("www.baeldung.com", imagePath));
resultGraphicsCentered.show();
ImagePlus resultGraphicsBottomRight = new ImagePlus("", signImageBottomRight("www.baeldung.com", imagePath));
resultGraphicsBottomRight.show();
ImagePlus resultGraphicsTopLeft = new ImagePlus("", signImageTopLeft("www.baeldung.com", imagePath));
resultGraphicsTopLeft.show();
ImagePlus resultGraphicsAdaptBasedOnImage = new ImagePlus("", signImageAdaptBasedOnImage("www.baeldung.com", imagePath));
resultGraphicsAdaptBasedOnImage.show();
}
private static ImagePlus signImageImageProcessor(String text, String path) {
ImagePlus image = IJ.openImage(path);
Font font = new Font("Arial", Font.BOLD, 18);
ImageProcessor ip = image.getProcessor();
ip.setColor(Color.GREEN);
ip.setFont(font);
ip.drawString(text, 0, 20);
return image;
}
private static BufferedImage signImageGraphics(String text, String path) throws IOException {
BufferedImage image = ImageIO.read(new File(path));
Font font = new Font("Arial", Font.BOLD, 18);
Graphics g = image.getGraphics();
g.setFont(font);
g.setColor(Color.GREEN);
g.drawString(text, 0, 20);
return image;
}
private static BufferedImage signImageGraphicsWithIterator(String text, String path) throws IOException {
BufferedImage image = ImageIO.read(new File(path));
Font font = new Font("Arial", Font.BOLD, 18);
AttributedString attributedText = new AttributedString(text);
attributedText.addAttribute(TextAttribute.FONT, font);
attributedText.addAttribute(TextAttribute.FOREGROUND, Color.GREEN);
Graphics g = image.getGraphics();
g.drawString(attributedText.getIterator(), 0, 20);
return image;
}
/**
* Draw a String centered in the middle of a Rectangle.
*
* @param g The Graphics instance.
* @param text The String to draw.
* @param rect The Rectangle to center the text in.
* @throws IOException
*/
public static BufferedImage signImageCenter(String text, String path) throws IOException {
BufferedImage image = ImageIO.read(new File(path));
Font font = new Font("Arial", Font.BOLD, 18);
AttributedString attributedText = new AttributedString(text);
attributedText.addAttribute(TextAttribute.FONT, font);
attributedText.addAttribute(TextAttribute.FOREGROUND, Color.GREEN);
Graphics g = image.getGraphics();
FontMetrics metrics = g.getFontMetrics(font);
int positionX = (image.getWidth() - metrics.stringWidth(text)) / 2;
int positionY = (image.getHeight() - metrics.getHeight()) / 2 + metrics.getAscent();
g.drawString(attributedText.getIterator(), positionX, positionY);
return image;
}
/**
* Draw a String centered in the middle of a Rectangle.
*
* @param g The Graphics instance.
* @param text The String to draw.
* @param rect The Rectangle to center the text in.
* @throws IOException
*/
public static BufferedImage signImageBottomRight(String text, String path) throws IOException {
BufferedImage image = ImageIO.read(new File(path));
Font font = new Font("Arial", Font.BOLD, 18);
AttributedString attributedText = new AttributedString(text);
attributedText.addAttribute(TextAttribute.FONT, font);
attributedText.addAttribute(TextAttribute.FOREGROUND, Color.GREEN);
Graphics g = image.getGraphics();
FontMetrics metrics = g.getFontMetrics(font);
int positionX = (image.getWidth() - metrics.stringWidth(text));
int positionY = (image.getHeight() - metrics.getHeight()) + metrics.getAscent();
g.drawString(attributedText.getIterator(), positionX, positionY);
return image;
}
/**
* Draw a String centered in the middle of a Rectangle.
*
* @param g The Graphics instance.
* @param text The String to draw.
* @param rect The Rectangle to center the text in.
* @throws IOException
*/
public static BufferedImage signImageTopLeft(String text, String path) throws IOException {
BufferedImage image = ImageIO.read(new File(path));
Font font = new Font("Arial", Font.BOLD, 18);
AttributedString attributedText = new AttributedString(text);
attributedText.addAttribute(TextAttribute.FONT, font);
attributedText.addAttribute(TextAttribute.FOREGROUND, Color.GREEN);
Graphics g = image.getGraphics();
FontMetrics metrics = g.getFontMetrics(font);
int positionX = 0;
int positionY = metrics.getAscent();
g.drawString(attributedText.getIterator(), positionX, positionY);
return image;
}
/**
* Draw a String centered in the middle of a Rectangle.
*
* @param g The Graphics instance.
* @param text The String to draw.
* @param rect The Rectangle to center the text in.
* @throws IOException
*/
public static BufferedImage signImageAdaptBasedOnImage(String text, String path) throws IOException {
BufferedImage image = ImageIO.read(new File(path));
Font font = createFontToFit(new Font("Arial", Font.BOLD, 80), text, image);
AttributedString attributedText = new AttributedString(text);
attributedText.addAttribute(TextAttribute.FONT, font);
attributedText.addAttribute(TextAttribute.FOREGROUND, Color.GREEN);
Graphics g = image.getGraphics();
FontMetrics metrics = g.getFontMetrics(font);
int positionX = (image.getWidth() - metrics.stringWidth(text));
int positionY = (image.getHeight() - metrics.getHeight()) + metrics.getAscent();
g.drawString(attributedText.getIterator(), positionX, positionY);
return image;
}
public static Font createFontToFit(Font baseFont, String text, BufferedImage image) throws IOException {
Font newFont = baseFont;
FontMetrics ruler = image.getGraphics().getFontMetrics(baseFont);
GlyphVector vector = baseFont.createGlyphVector(ruler.getFontRenderContext(), text);
Shape outline = vector.getOutline(0, 0);
double expectedWidth = outline.getBounds().getWidth();
double expectedHeight = outline.getBounds().getHeight();
boolean textFits = image.getWidth() >= expectedWidth && image.getHeight() >= expectedHeight;
if (!textFits) {
double widthBasedFontSize = (baseFont.getSize2D() * image.getWidth()) / expectedWidth;
double heightBasedFontSize = (baseFont.getSize2D() * image.getHeight()) / expectedHeight;
double newFontSize = widthBasedFontSize < heightBasedFontSize ? widthBasedFontSize : heightBasedFontSize;
newFont = baseFont.deriveFont(baseFont.getStyle(), (float) newFontSize);
}
return newFont;
}
}

View File

@ -0,0 +1,22 @@
package com.baeldung.imageprocessing.imagej;
import ij.IJ;
import ij.ImagePlus;
import ij.process.ImageProcessor;
import java.awt.*;
public class ImageJRectExample {
public static void main(String[] args) {
ImagePlus imp = IJ.openImage(ImageJRectExample.class.getClassLoader().getResource("lena.jpg").getPath());
drawRect(imp);
imp.show();
}
private static void drawRect(ImagePlus imp) {
ImageProcessor ip = imp.getProcessor();
ip.setColor(Color.BLUE);
ip.setLineWidth(4);
ip.drawRect(10, 10, imp.getWidth() - 20, imp.getHeight() - 20);
}
}

View File

@ -0,0 +1,87 @@
package com.baeldung.imageprocessing.opencv;
import javafx.animation.AnimationTimer;
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.layout.HBox;
import javafx.stage.Stage;
import org.opencv.core.Mat;
import org.opencv.core.MatOfByte;
import org.opencv.core.MatOfRect;
import org.opencv.core.Rect;
import org.opencv.core.Scalar;
import org.opencv.core.Size;
import org.opencv.imgcodecs.Imgcodecs;
import org.opencv.imgproc.Imgproc;
import org.opencv.objdetect.CascadeClassifier;
import org.opencv.objdetect.Objdetect;
import org.opencv.videoio.VideoCapture;
import java.io.ByteArrayInputStream;
public class CameraStream extends Application {
private VideoCapture capture;
public void start(Stage stage) throws Exception {
// OpenCV.loadShared();
capture= new VideoCapture(0); // The number is the ID of the camera
ImageView imageView = new ImageView();
HBox hbox = new HBox(imageView);
Scene scene = new Scene(hbox);
stage.setScene(scene);
stage.show();
new AnimationTimer(){
@Override
public void handle(long l) {
imageView.setImage(getCapture());
}
}.start();
}
public Image getCapture() {
Mat mat = new Mat();
capture.read(mat);
return mat2Img(mat);
}
public Image getCaptureWithFaceDetection() {
Mat mat = new Mat();
capture.read(mat);
Mat haarClassifiedImg = detectFace(mat);
return mat2Img(haarClassifiedImg);
}
public Image mat2Img(Mat mat) {
MatOfByte bytes = new MatOfByte();
Imgcodecs.imencode("img", mat, bytes);
ByteArrayInputStream inputStream = new ByteArrayInputStream(bytes.toArray());
Image img = new Image(inputStream); return img;
}
public static void main(String[] args) {
Application.launch(args);
}
public static Mat detectFace(Mat inputImage) {
MatOfRect facesDetected = new MatOfRect();
CascadeClassifier cascadeClassifier = new CascadeClassifier();
int minFaceSize = Math.round(inputImage.rows() * 0.1f);
cascadeClassifier.load("./src/main/resources/haarcascades/haarcascade_frontalface_alt.xml");
cascadeClassifier.detectMultiScale(inputImage,
facesDetected,
1.1,
3,
Objdetect.CASCADE_SCALE_IMAGE,
new Size(minFaceSize, minFaceSize),
new Size()
);
Rect[] facesArray = facesDetected.toArray();
for(Rect face : facesArray) {
Imgproc.rectangle(inputImage, face.tl(), face.br(), new Scalar(0, 0, 255), 3 );
}
return inputImage;
}
}

View File

@ -0,0 +1,56 @@
package com.baeldung.imageprocessing.opencv;
import org.opencv.core.Mat;
import org.opencv.core.MatOfByte;
import org.opencv.core.MatOfRect;
import org.opencv.core.Rect;
import org.opencv.core.Scalar;
import org.opencv.core.Size;
import org.opencv.imgcodecs.Imgcodecs;
import org.opencv.imgproc.Imgproc;
import org.opencv.objdetect.CascadeClassifier;
import org.opencv.objdetect.Objdetect;
import javafx.scene.image.Image;
import java.io.ByteArrayInputStream;
public class FaceDetection {
public static Mat loadImage(String imagePath) {
Imgcodecs imageCodecs = new Imgcodecs();
return imageCodecs.imread(imagePath);
}
public static void saveImage(Mat imageMatrix, String targetPath) {
Imgcodecs imgcodecs = new Imgcodecs();
imgcodecs.imwrite(targetPath, imageMatrix);
}
public static void detectFace(String sourceImagePath, String targetImagePath) {
Mat loadedImage = loadImage(sourceImagePath);
MatOfRect facesDetected = new MatOfRect();
CascadeClassifier cascadeClassifier = new CascadeClassifier();
int minFaceSize = Math.round(loadedImage.rows() * 0.1f);
cascadeClassifier.load("./src/main/resources/haarcascades/haarcascade_frontalface_alt.xml");
cascadeClassifier.detectMultiScale(loadedImage,
facesDetected,
1.1,
3,
Objdetect.CASCADE_SCALE_IMAGE,
new Size(minFaceSize, minFaceSize),
new Size()
);
Rect[] facesArray = facesDetected.toArray();
for(Rect face : facesArray) {
Imgproc.rectangle(loadedImage, face.tl(), face.br(), new Scalar(0, 0, 255), 3 );
}
saveImage(loadedImage, targetImagePath);
}
public Image mat2Img(Mat mat) {
MatOfByte bytes = new MatOfByte();
Imgcodecs.imencode("img", mat, bytes);
ByteArrayInputStream inputStream = new ByteArrayInputStream(bytes.toArray());
Image img = new Image(inputStream); return img;
}
}

View File

@ -0,0 +1,28 @@
package com.baeldung.imageprocessing.openimaj;
import org.openimaj.image.DisplayUtilities;
import org.openimaj.image.ImageUtilities;
import org.openimaj.image.MBFImage;
import org.openimaj.math.geometry.point.Point2d;
import org.openimaj.math.geometry.point.Point2dImpl;
import org.openimaj.math.geometry.shape.Polygon;
import java.io.IOException;
import java.util.Arrays;
public class OpenIMAJRectExample {
public static void main(String[] args) throws IOException {
MBFImage image = ImageUtilities.readMBF(OpenIMAJRectExample.class.getClassLoader().getResource("lena.jpg"));
drawRectangle(image);
DisplayUtilities.display(image);
}
private static void drawRectangle(MBFImage image) {
Point2d tl = new Point2dImpl(10, 10);
Point2d bl = new Point2dImpl(10, image.getHeight() - 10);
Point2d br = new Point2dImpl(image.getWidth() - 10, image.getHeight() - 10);
Point2d tr = new Point2dImpl(image.getWidth() - 10, 10);
Polygon polygon = new Polygon(Arrays.asList(tl, bl, br, tr));
image.drawPolygon(polygon, 4, new Float[] { 0f, 0f, 255.0f });
}
}

View File

@ -0,0 +1,40 @@
package com.baeldung.imageprocessing.swing;
import javax.imageio.ImageIO;
import javax.swing.*;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
public class SwingRectExample {
public static void main(String[] args) throws IOException {
BufferedImage image = loadImage();
drawRectangle(image);
displayImage(image);
}
private static BufferedImage loadImage() throws IOException {
String imagePath = SwingRectExample.class.getClassLoader().getResource("lena.jpg").getPath();
return ImageIO.read(new File(imagePath));
}
private static void drawRectangle(BufferedImage image) {
Graphics2D g = (Graphics2D) image.getGraphics();
g.setStroke(new BasicStroke(3));
g.setColor(Color.BLUE);
g.drawRect(10, 10, image.getWidth() - 20, image.getHeight() - 20);
}
private static void displayImage(BufferedImage image) {
JLabel picLabel = new JLabel(new ImageIcon(image));
JPanel jPanel = new JPanel();
jPanel.add(picLabel);
JFrame f = new JFrame();
f.setSize(new Dimension(image.getWidth(), image.getHeight()));
f.add(jPanel);
f.setVisible(true);
}
}

View File

@ -0,0 +1,47 @@
package com.baeldung.imageprocessing.twelvemonkeys;
import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
public class TwelveMonkeysExample {
public static void main(String[] args) throws IOException {
BufferedImage image = loadImage();
drawRectangle(image);
displayImage(image);
}
private static BufferedImage loadImage() throws IOException {
String imagePath = TwelveMonkeysExample.class.getClassLoader().getResource("Penguin.ico").getPath();
return ImageIO.read(new File(imagePath));
}
private static void drawRectangle(BufferedImage image) {
Graphics2D g = (Graphics2D) image.getGraphics();
g.setStroke(new BasicStroke(3));
g.setColor(Color.BLUE);
g.drawRect(10, 10, image.getWidth() - 20, image.getHeight() - 20);
}
private static void displayImage(BufferedImage image) {
JLabel picLabel = new JLabel(new ImageIcon(image));
JPanel jPanel = new JPanel();
jPanel.add(picLabel);
JFrame f = new JFrame();
f.setSize(new Dimension(200, 200));
f.add(jPanel);
f.setVisible(true);
}
}

View File

@ -0,0 +1,28 @@
package com.baeldung.tesseract;
import java.awt.Rectangle;
import java.io.File;
import net.sourceforge.tess4j.Tesseract;
import net.sourceforge.tess4j.TesseractException;
public class Tess4JExample {
public static void main(String[] args) {
String result = null;
try {
File image = new File("src/main/resources/images/baeldung.png");
Tesseract tesseract = new Tesseract();
tesseract.setLanguage("spa");
tesseract.setPageSegMode(1);
tesseract.setOcrEngineMode(1);
tesseract.setHocr(true);
tesseract.setDatapath("src/main/resources/tessdata");
result = tesseract.doOCR(image, new Rectangle(1200, 200));
} catch (TesseractException e) {
e.printStackTrace();
}
System.out.println(result);
}
}

View File

@ -0,0 +1,26 @@
package com.baeldung.tesseract;
import org.bytedeco.javacpp.BytePointer;
import org.bytedeco.leptonica.PIX;
import org.bytedeco.tesseract.TessBaseAPI;
public class TesseractPlatformExample {
@SuppressWarnings("resource")
public static void main(String[] args) {
try {
TessBaseAPI tessApi = new TessBaseAPI();
tessApi.Init("src/main/resources/tessdata", "eng", 3);
tessApi.SetPageSegMode(1);
PIX image = org.bytedeco.leptonica.global.lept.pixRead("src/main/resources/images/baeldung.png");
tessApi.SetImage(image);
BytePointer outText = tessApi.GetUTF8Text();
System.out.println(outText.getString());
tessApi.End();
} catch(Exception e) {
e.printStackTrace();
}
}
}

Binary file not shown.

After

Width:  |  Height:  |  Size: 164 KiB

File diff suppressed because it is too large Load Diff

Binary file not shown.

After

Width:  |  Height:  |  Size: 648 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 217 KiB

View File

@ -0,0 +1,9 @@
Der ,.schnelle” braune Fuchs springt
iiber den faulen Hund. Le renard brun
«rapide» saute par-dessus le chien
paresseux. La volpe marrone rapida
salta sopra il cane pigro. El zorro
marron rapido salta sobre el perro
perezoso. A raposa marrom rapida
salta sobre 0 cao preguicoso.

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.1 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 93 KiB

View File

@ -0,0 +1,13 @@
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
</pattern>
</encoder>
</appender>
<root level="INFO">
<appender-ref ref="STDOUT" />
</root>
</configuration>

View File

@ -0,0 +1,71 @@
package com.baeldung.image.resize.core;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotEquals;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import org.junit.Test;
public class Graphics2DExampleUnitTest {
@Test(expected = Test.None.class)
public void whenOriginalImageExistsAndTargetSizesAreNotZero_thenImageGeneratedWithoutError() throws IOException {
int targetWidth = 200;
int targetHeight = 200;
BufferedImage originalImage = ImageIO.read(new File("src/main/resources/images/sampleImage.jpg"));
BufferedImage outputImage = Graphics2DExample.resizeImage(originalImage, targetWidth, targetHeight);
assertNotNull(outputImage);
}
@Test(expected = Test.None.class)
public void whenOriginalImageExistsAndTargetSizesAreNotZero_thenOutputImageSizeIsValid() throws IOException {
int targetWidth = 200;
int targetHeight = 200;
BufferedImage originalImage = ImageIO.read(new File("src/main/resources/images/sampleImage.jpg"));
assertNotEquals(originalImage.getWidth(), targetWidth);
assertNotEquals(originalImage.getHeight(), targetHeight);
BufferedImage outputImage = Graphics2DExample.resizeImage(originalImage, targetWidth, targetHeight);
assertEquals(outputImage.getWidth(), targetWidth);
assertEquals(outputImage.getHeight(), targetHeight);
}
@Test(expected = Exception.class)
public void whenTargetWidthIsZero_thenErrorIsThrown() throws IOException {
int targetWidth = 0;
int targetHeight = 200;
BufferedImage originalImage = ImageIO.read(new File("src/main/resources/images/sampleImage.jpg"));
BufferedImage outputImage = Graphics2DExample.resizeImage(originalImage, targetWidth, targetHeight);
assertNull(outputImage);
}
@Test(expected = Exception.class)
public void whenTargetHeightIsZero_thenErrorIsThrown() throws IOException {
int targetWidth = 200;
int targetHeight = 0;
BufferedImage originalImage = ImageIO.read(new File("src/main/resources/images/sampleImage.jpg"));
BufferedImage outputImage = Graphics2DExample.resizeImage(originalImage, targetWidth, targetHeight);
assertNull(outputImage);
}
@Test(expected = Test.None.class)
public void whenOriginalImageDoesNotExist_thenErrorIsNotThrownAndImageIsGenerated() throws IOException {
int targetWidth = 200;
int targetHeight = 200;
BufferedImage outputImage = Graphics2DExample.resizeImage(null, targetWidth, targetHeight);
assertNotNull(outputImage);
assertEquals(outputImage.getWidth(), targetWidth);
assertEquals(outputImage.getHeight(), targetHeight);
}
}

View File

@ -0,0 +1,69 @@
package com.baeldung.image.resize.core;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotEquals;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import org.junit.Test;
public class ImageScaledInstanceExampleUnitTest {
@Test(expected = Test.None.class)
public void whenOriginalImageExistsAndTargetSizesAreNotZero_thenImageGeneratedWithoutError() throws IOException {
int targetWidth = 200;
int targetHeight = 200;
BufferedImage originalImage = ImageIO.read(new File("src/main/resources/images/sampleImage.jpg"));
BufferedImage outputImage = ImageScaledInstanceExample.resizeImage(originalImage, targetWidth, targetHeight);
assertNotNull(outputImage);
}
@Test(expected = Test.None.class)
public void whenOriginalImageExistsAndTargetSizesAreNotZero_thenOutputImageSizeIsValid() throws IOException {
int targetWidth = 200;
int targetHeight = 200;
BufferedImage originalImage = ImageIO.read(new File("src/main/resources/images/sampleImage.jpg"));
assertNotEquals(originalImage.getWidth(), targetWidth);
assertNotEquals(originalImage.getHeight(), targetHeight);
BufferedImage outputImage = ImageScaledInstanceExample.resizeImage(originalImage, targetWidth, targetHeight);
assertEquals(outputImage.getWidth(), targetWidth);
assertEquals(outputImage.getHeight(), targetHeight);
}
@Test(expected = Exception.class)
public void whenTargetWidthIsZero_thenErrorIsThrown() throws IOException {
int targetWidth = 0;
int targetHeight = 200;
BufferedImage originalImage = ImageIO.read(new File("src/main/resources/images/sampleImage.jpg"));
BufferedImage outputImage = ImageScaledInstanceExample.resizeImage(originalImage, targetWidth, targetHeight);
assertNull(outputImage);
}
@Test(expected = Exception.class)
public void whenTargetHeightIsZero_thenErrorIsThrown() throws IOException {
int targetWidth = 200;
int targetHeight = 0;
BufferedImage originalImage = ImageIO.read(new File("src/main/resources/images/sampleImage.jpg"));
BufferedImage outputImage = ImageScaledInstanceExample.resizeImage(originalImage, targetWidth, targetHeight);
assertNull(outputImage);
}
@Test(expected = Exception.class)
public void whenOriginalImageDoesNotExist_thenErrorIsThrown() throws IOException {
int targetWidth = 200;
int targetHeight = 200;
BufferedImage outputImage = ImageScaledInstanceExample.resizeImage(null, targetWidth, targetHeight);
assertNull(outputImage);
}
}

View File

@ -0,0 +1,69 @@
package com.baeldung.image.resize.imgscalr;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotEquals;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import org.junit.Test;
public class ImgscalrExampleUnitTest {
@Test(expected = Test.None.class)
public void whenOriginalImageExistsAndTargetSizesAreNotZero_thenImageGeneratedWithoutError() throws IOException {
int targetWidth = 200;
int targetHeight = 200;
BufferedImage originalImage = ImageIO.read(new File("src/main/resources/images/sampleImage.jpg"));
BufferedImage outputImage = ImgscalrExample.resizeImage(originalImage, targetWidth, targetHeight);
assertNotNull(outputImage);
}
@Test(expected = Test.None.class)
public void whenOriginalImageExistsAndTargetSizesAreNotZero_thenOutputImageSizeIsValid() throws IOException {
int targetWidth = 200;
int targetHeight = 200;
BufferedImage originalImage = ImageIO.read(new File("src/main/resources/images/sampleImage.jpg"));
assertNotEquals(originalImage.getWidth(), targetWidth);
assertNotEquals(originalImage.getHeight(), targetHeight);
BufferedImage outputImage = ImgscalrExample.resizeImage(originalImage, targetWidth, targetHeight);
assertEquals(outputImage.getWidth(), targetWidth);
assertEquals(outputImage.getHeight(), targetHeight);
}
@Test(expected = Test.None.class)
public void whenTargetWidthIsZero_thenImageIsCreated() throws IOException {
int targetWidth = 0;
int targetHeight = 200;
BufferedImage originalImage = ImageIO.read(new File("src/main/resources/images/sampleImage.jpg"));
BufferedImage outputImage = ImgscalrExample.resizeImage(originalImage, targetWidth, targetHeight);
assertNotNull(outputImage);
}
@Test(expected = Test.None.class)
public void whenTargetHeightIsZero_thenImageIsCreated() throws IOException {
int targetWidth = 200;
int targetHeight = 0;
BufferedImage originalImage = ImageIO.read(new File("src/main/resources/images/sampleImage.jpg"));
BufferedImage outputImage = ImgscalrExample.resizeImage(originalImage, targetWidth, targetHeight);
assertNotNull(outputImage);
}
@Test(expected = Exception.class)
public void whenOriginalImageDoesNotExist_thenErrorIsThrown() {
int targetWidth = 200;
int targetHeight = 200;
BufferedImage outputImage = ImgscalrExample.resizeImage(null, targetWidth, targetHeight);
assertNull(outputImage);
}
}

View File

@ -0,0 +1,68 @@
package com.baeldung.image.resize.marvin;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotEquals;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import org.junit.Test;
public class MarvinExampleUnitTest {
@Test(expected = Test.None.class)
public void whenOriginalImageExistsAndTargetSizesAreNotZero_thenImageGeneratedWithoutError() throws IOException {
int targetWidth = 200;
int targetHeight = 200;
BufferedImage originalImage = ImageIO.read(new File("src/main/resources/images/sampleImage.jpg"));
BufferedImage outputImage = MarvinExample.resizeImage(originalImage, targetWidth, targetHeight);
assertNotNull(outputImage);
}
@Test(expected = Test.None.class)
public void whenOriginalImageExistsAndTargetSizesAreNotZero_thenOutputImageSizeIsValid() throws IOException {
int targetWidth = 200;
int targetHeight = 200;
BufferedImage originalImage = ImageIO.read(new File("src/main/resources/images/sampleImage.jpg"));
assertNotEquals(originalImage.getWidth(), targetWidth);
assertNotEquals(originalImage.getHeight(), targetHeight);
BufferedImage outputImage = MarvinExample.resizeImage(originalImage, targetWidth, targetHeight);
assertEquals(outputImage.getWidth(), targetWidth);
assertEquals(outputImage.getHeight(), targetHeight);
}
@Test(expected = Exception.class)
public void whenTargetWidthIsZero_thenErrorIsThrown() throws IOException {
int targetWidth = 0;
int targetHeight = 200;
BufferedImage originalImage = ImageIO.read(new File("src/main/resources/images/sampleImage.jpg"));
BufferedImage outputImage = MarvinExample.resizeImage(originalImage, targetWidth, targetHeight);
assertNull(outputImage);
}
@Test(expected = Exception.class)
public void whenTargetHeightIsZero_thenErrorIsThrown() throws IOException {
int targetWidth = 200;
int targetHeight = 0;
BufferedImage originalImage = ImageIO.read(new File("src/main/resources/images/sampleImage.jpg"));
BufferedImage outputImage = MarvinExample.resizeImage(originalImage, targetWidth, targetHeight);
assertNull(outputImage);
}
@Test(expected = Exception.class)
public void whenOriginalImageDoesNotExist_thenErrorIsThrown() {
int targetWidth = 200;
int targetHeight = 200;
BufferedImage outputImage = MarvinExample.resizeImage(null, targetWidth, targetHeight);
assertNull(outputImage);
}
}

View File

@ -0,0 +1,68 @@
package com.baeldung.image.resize.thumbnailator;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotEquals;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import org.junit.Test;
public class ThumbnailatorExampleUnitTest {
@Test(expected = Test.None.class)
public void whenOriginalImageExistsAndTargetSizesAreNotZero_thenImageGeneratedWithoutError() throws IOException {
int targetWidth = 200;
int targetHeight = 200;
BufferedImage originalImage = ImageIO.read(new File("src/main/resources/images/sampleImage.jpg"));
BufferedImage outputImage = ThumbnailatorExample.resizeImage(originalImage, targetWidth, targetHeight);
assertNotNull(outputImage);
}
@Test(expected = Test.None.class)
public void whenOriginalImageExistsAndTargetSizesAreNotZero_thenOutputImageSizeIsValid() throws IOException {
int targetWidth = 200;
int targetHeight = 200;
BufferedImage originalImage = ImageIO.read(new File("src/main/resources/images/sampleImage.jpg"));
assertNotEquals(originalImage.getWidth(), targetWidth);
assertNotEquals(originalImage.getHeight(), targetHeight);
BufferedImage outputImage = ThumbnailatorExample.resizeImage(originalImage, targetWidth, targetHeight);
assertEquals(outputImage.getWidth(), targetWidth);
assertEquals(outputImage.getHeight(), targetHeight);
}
@Test(expected = Exception.class)
public void whenTargetWidthIsZero_thenErrorIsThrown() throws IOException {
int targetWidth = 0;
int targetHeight = 200;
BufferedImage originalImage = ImageIO.read(new File("src/main/resources/images/sampleImage.jpg"));
BufferedImage outputImage = ThumbnailatorExample.resizeImage(originalImage, targetWidth, targetHeight);
assertNull(outputImage);
}
@Test(expected = Exception.class)
public void whenTargetHeightIsZero_thenErrorIsThrown() throws IOException {
int targetWidth = 200;
int targetHeight = 0;
BufferedImage originalImage = ImageIO.read(new File("src/main/resources/images/sampleImage.jpg"));
BufferedImage outputImage = ThumbnailatorExample.resizeImage(originalImage, targetWidth, targetHeight);
assertNull(outputImage);
}
@Test(expected = Exception.class)
public void whenOriginalImageDoesNotExist_thenErrorIsThrown() throws IOException {
int targetWidth = 200;
int targetHeight = 200;
BufferedImage outputImage = ThumbnailatorExample.resizeImage(null, targetWidth, targetHeight);
assertNull(outputImage);
}
}

17
pom.xml
View File

@ -40,6 +40,7 @@
<modules>
<module>core-java-modules</module>
<module>image-processing</module>
<!-- <module>jackson-modules</module>-->
<!-- <module>jackson-simple</module>-->
<!-- <module>parent-java</module>-->
@ -57,7 +58,8 @@
<!-- Logging -->
<version.slf4j>1.7.36</version.slf4j>
<version.log4j>1.2.17</version.log4j>
<log4j.version>1.2.17</log4j.version>
<log4j-over-slf4j.version>2.0.7</log4j-over-slf4j.version>
<version.log4j2>2.18.0</version.log4j2>
<!-- APACHE COMMONS-->
@ -73,6 +75,8 @@
<!-- UTILS -->
<version.guava>31.1-jre</version.guava>
<lombok.version>1.18.28</lombok.version>
<joda-time.version>2.12.5</joda-time.version>
<!-- Hibernate / JPA -->
<hibernate.version>4.3.5.Final</hibernate.version>
@ -105,7 +109,7 @@
<!-- CDN & CLOUD -->
<jclouds.version>1.9.0</jclouds.version>
<modelmapper.version>2.4.4</modelmapper.version>
<lombok.version>1.18.20</lombok.version>
<moneta.version>1.3</moneta.version>
<jmh-core.version>1.33</jmh-core.version>
<exec-maven-plugin.version>3.0.0</exec-maven-plugin.version>
@ -148,19 +152,24 @@
<artifactId>commons-io</artifactId>
<version>${commons-io.version}</version>
</dependency>
<dependency>
<groupId>org.apache.velocity</groupId>
<artifactId>velocity-engine-core</artifactId>
<version>2.3</version>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.13</version>
</dependency>
<dependency>
<groupId>antlr</groupId>
<artifactId>antlr</artifactId>
<version>2.7.6</version>
</dependency>
<!-- utils -->
<!-- UTILS -->
<dependency>
<groupId>org.dom4j</groupId>
<artifactId>dom4j</artifactId>

View File

@ -1,56 +0,0 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>CORS TESTING</title>
<!-- Required meta tags -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<!-- Bootstrap CSS -->
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
</head>
<body>
<div class="container">
<h1>CORS TESTING</h1>
<!-- Content here -->
<p class="text-left">Update to your target API address:</p>
<input type="text" style="width:600px;height:30px;font-size:14px;" id="urlText" value="http://localhost:8080/search/user"/>
<p>&nbsp;
<p/>
<p class="text-left">Update to your Bearer Token:</p>
<input type="text" style="width:600px;height:30px;font-size:14px;" id="tokenTxt" value=""/>
<p>&nbsp;
<p/>
<input type="button" class="btn btn-outline-primary" id="cors" value="CHECK CORS"/>
</div>
<!-- Optional JavaScript -->
<!-- jQuery first, then Popper.js, then Bootstrap JS -->
<script src="https://code.jquery.com/jquery-3.4.1.min.js" integrity="sha256-CSXorXvZcTkaix6Yvo6HppcZGetbYMGWSFlBw8HfCJo=" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js" integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"></script>
<script type="text/javascript">
$("#cors").on('click', function (event) {
event.preventDefault();
var url2 = $("#urlText").val();
$.get({
contentType: 'application/x-www-form-urlencoded;charset=UTF-8',
url: url2,
beforeSend: function (xhr) {
if ($("#tokenTxt").val().trim()) {
/* Authorization header */
xhr.setRequestHeader("Authorization", "Bearer " + $("#tokenTxt").val());
}
},
success: function (data) {
alert("success");
}
})
});
</script>
</body>
</html>

View File

@ -1,97 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE RelativeLayout>
<Configuration status="WARN">
<Properties>
<Property name="baseDir">/home/logs/reoc/services/</Property>
</Properties>
<Appenders>
<!-- ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ -->
<!-- C O N S O L E - A P P E N D E R -->
<!-- ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ -->
<Console name="CONSOLE" target="SYSTEM_OUT">
<PatternLayout pattern="%-d{yyyy/MM/dd HH:mm:ss} %-5p [%c] - %m%n" />
<ThresholdFilter level="TRACE" onMatch="ACCEPT" onMismatch="DENY" />
</Console>
<!-- ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ -->
<!-- D E B U G _ F I L E - A P P E N D E R -->
<!-- ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ -->
<RollingFile name="FILE_DEBUG" append="true" fileName="${baseDir}/services_debug.log" filePattern="${baseDir}/$${date:yyyy-MM}/services-debug-%d{yyyy-MM-dd}-%i.log.gz">
<ThresholdFilter level="DEBUG" onMatch="ACCEPT" onMismatch="DENY" />
<PatternLayout>
<pattern>%-d{yyyy/MM/dd HH:mm:ss} %-5p [%c] - %m%n</pattern>
</PatternLayout>
<Policies>
<TimeBasedTriggeringPolicy />
<SizeBasedTriggeringPolicy size="250 MB"></SizeBasedTriggeringPolicy>
</Policies>
<DefaultRolloverStrategy max="12" />
</RollingFile>
<!-- ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ -->
<!-- I N F O _ F I L E - A P P E N D E R -->
<!-- ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ -->
<RollingFile name="FILE_INFO" append="true" fileName="${baseDir}/services_info.log" filePattern="${baseDir}/$${date:yyyy-MM}/services-info-%d{yyyy-MM-dd}.log.gz">
<ThresholdFilter level="INFO" onMatch="ACCEPT" onMismatch="DENY" />
<PatternLayout>
<pattern>%-d{yyyy/MM/dd HH:mm:ss} %-5p [%c] - %m%n</pattern>
</PatternLayout>
<Policies>
<TimeBasedTriggeringPolicy />
<SizeBasedTriggeringPolicy size="250 MB"></SizeBasedTriggeringPolicy>
</Policies>
<DefaultRolloverStrategy max="12" />
</RollingFile>
<!-- ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ -->
<!-- F I L E _ W A R N - A P P E N D E R -->
<!-- ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ -->
<RollingFile name="FILE_WARN" append="true" fileName="${baseDir}/services_info.log" filePattern="${baseDir}/$${date:yyyy-MM}/services-warn-%d{yyyy-MM-dd}.log.gz">
<ThresholdFilter level="WARN" onMatch="ACCEPT" onMismatch="DENY" />
<PatternLayout>
<pattern>%-d{yyyy/MM/dd HH:mm:ss} %-5p [%c] - %m%n</pattern>
</PatternLayout>
<Policies>
<TimeBasedTriggeringPolicy />
<SizeBasedTriggeringPolicy size="250 MB"></SizeBasedTriggeringPolicy>
</Policies>
<DefaultRolloverStrategy max="12" />
</RollingFile>
<!-- ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ -->
<!-- F I L E _ E R R O R - A P P E N D E R -->
<!-- ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ -->
<RollingFile name="FILE_ERROR" append="true" fileName="${baseDir}/services_error.log" filePattern="${baseDir}/$${date:yyyy-MM}/services-error-%d{yyyy-MM-dd}.log.gz">
<ThresholdFilter level="ERROR" onMatch="ACCEPT" onMismatch="DENY" />
<PatternLayout>
<pattern>%-d{yyyy/MM/dd HH:mm:ss} %-5p [%c] - %m%n</pattern>
</PatternLayout>
<Policies>
<TimeBasedTriggeringPolicy />
<SizeBasedTriggeringPolicy size="250 MB"></SizeBasedTriggeringPolicy>
</Policies>
<DefaultRolloverStrategy max="12" />
</RollingFile>
</Appenders>
<!-- LOGGERS -->
<Loggers>
<Logger name="com.ossez" level="TRACE" additivity="false">
<AppenderRef ref="CONSOLE" level="DEBUG" />
<AppenderRef ref="FILE_DEBUG" level="DEBUG" />
<AppenderRef ref="FILE_INFO" level="INFO" />
<AppenderRef ref="FILE_WARN" level="WARN" />
<AppenderRef ref="FILE_ERROR" level="ERROR" />
</Logger>
<root level="TRACE">
</root>
</Loggers>
</Configuration>

View File

@ -1,6 +0,0 @@
Jill,Doe
Joe,Doe
Justin,Doe
Jane,Doe
John,Doe
YuCheng,HU
1 Jill Doe
Jill Doe
Joe Doe
Justin Doe
Jane Doe
John Doe
YuCheng HU

View File

@ -1,7 +0,0 @@
DROP TABLE people IF EXISTS;
CREATE TABLE people (
person_id BIGINT IDENTITY NOT NULL PRIMARY KEY,
first_name VARCHAR(20),
last_name VARCHAR(20)
);

View File

@ -1,36 +0,0 @@
#!/bin/sh
cd $(dirname $0)
cd ../complete
mvn clean package
ret=$?
if [ $ret -ne 0 ]; then
exit $ret
fi
rm -rf target
./gradlew build
ret=$?
if [ $ret -ne 0 ]; then
exit $ret
fi
rm -rf build
cd ../initial
mvn clean compile
ret=$?
if [ $ret -ne 0 ]; then
exit $ret
fi
rm -rf target
./gradlew compileJava
ret=$?
if [ $ret -ne 0 ]; then
exit $ret
fi
rm -rf build
exit