I have a logic that takes images from f-end via byte[] in java, compress them and then store in Postgresql db in a column define with data lob.
Service:
public CourseDto createNewCourse(CourseDto newCourseDto) throws SQLException {
Courses course = courseRepositoryDao.findByCourseName(newCourseDto.getCourseName());
if (course == null) {
course = new Courses()
.setCourseName(newCourseDto.getCourseName())
.setCourseDescription(newCourseDto.getCourseDescription())
.setCoursePrice(newCourseDto.getCoursePrice())
.setIsCourseFree(newCourseDto.getIsCourseFree())
.setIsCourseActive(newCourseDto.getIsCourseActive())
.setLogo(compressZLib(newCourseDto.getLogo()));
;
return CourseMapper.toUserDtoFreeCourses(courseRepositoryDao.save(course));
}
throw exception(EntityType.NEWCOURSE, ExceptionType.DUPLICATE_ENTITY, newCourseDto.getCourseName());
}
// compress the image bytes before storing it in the database
public static byte[] compressZLib(byte[] data) {
Deflater deflater = new Deflater();
deflater.setInput(data);
deflater.finish();
ByteArrayOutputStream outputStream = new ByteArrayOutputStream(data.length);
byte[] buffer = new byte[1024];
while (!deflater.finished()) {
int count = deflater.deflate(buffer);
outputStream.write(buffer, 0, count);
}
try {
outputStream.close();
} catch (IOException e) {
}
System.out.println("Compressed Image Byte Size - " + outputStream.toByteArray().length);
return outputStream.toByteArray();
}
I try to retrieve the images:
public List<CourseDto> getCoureses() {
List<Courses> courses = courseRepositoryDao.findAllByIsCourseFreeAndIsCourseActive(true, true);
List<CourseDto> coursesNameDto = courses
.stream()
.peek(i -> i.setLogo(decompressZLib(i.getLogo())))
.map(course -> modelMapper.map(CourseMapper.toUserDtoFreeCourses(course), CourseDto.class)).collect(Collectors.toList());
System.out.println("**************************" + coursesNameDto + "**********************");
return coursesNameDto;
}
// uncompress the image bytes before returning it to the angular application
public static byte[] decompressZLib(byte[] data) {
Inflater inflater = new Inflater();
inflater.setInput(data);
ByteArrayOutputStream outputStream = new ByteArrayOutputStream(data.length);
byte[] buffer = new byte[1024];
try {
while (!inflater.finished()) {
int count = inflater.inflate(buffer);
outputStream.write(buffer, 0, count);
}
outputStream.close();
} catch (IOException ioe) {
} catch (DataFormatException e) {
}
return outputStream.toByteArray();
}
But I have this error: "Objects may not be used in auto-commit mode"
My entity class has this field on logo:
@Column(name = "picByte", length = 4000)
@Lob
private byte[] logo;