opencv/src/main/java/pl/edu/amu/wmi/bookapi/service/ImageProcessingService.java

60 lines
1.5 KiB
Java

package pl.edu.amu.wmi.bookapi.service;
import org.opencv.core.Core;
import org.opencv.core.Mat;
import org.opencv.core.MatOfByte;
import org.opencv.imgcodecs.Imgcodecs;
import org.opencv.imgproc.Imgproc;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.UUID;
import static java.lang.System.loadLibrary;
import static org.opencv.imgproc.Imgproc.COLOR_BGR2GRAY;
@Service
public class ImageProcessingService {
public ImageProcessingService() {
}
public String getDecodedEan(MultipartFile imageFile) throws Exception {
String fileId = UUID.randomUUID().toString();
Path path = Path.of(new File(".").getCanonicalPath());
byte[] starting = imageFile.getBytes();
saveImg(starting, path, fileId, 1);
Mat mat = Imgcodecs.imdecode(new MatOfByte(starting), Imgcodecs.CV_LOAD_IMAGE_UNCHANGED);
Mat gray = new Mat();
Imgproc.cvtColor(mat, gray, COLOR_BGR2GRAY);
byte[] grayed = mat2byteArr(gray);
saveImg(grayed, path, fileId, 2);
return "";
}
private byte[] mat2byteArr(Mat mat) {
byte[] bytes = new byte[0];
mat.get(0, 0, bytes);
return bytes;
}
private void saveImg(byte[] bytes, Path path, String imageName, Integer version) throws IOException {
Files.write(Path.of(path.toString(), "/" + imageName + "__v" + version + ".png"), bytes);
}
}