I get a image as byte on my server, i want to create a smaller image of it to use it as thumbnail. I want to avoid having to use javafx. Is that possible?
If you can get that image to be uncompressed, ie a 2D array of pixels, then: no worries.
The simplest algorithm is sampling every nth row and column to reduce the image to 1/nth of original size.
The next-simplest is to average each n-x-n block of pixels to produce 1 pixel in the 1/nth thumbnail.
If the thumbnail is not an integer reduction (?) of the original image, then it gets a little trickier if you want to be exactly correct, but in reality is probably a case of: close enough is good enough.
I wrapped a library called Thumbnailator to do just this. I have used it a while so the library may be out of date but it worked when I used it - edit: actually I see it had a release recently so Ive recompiled against that version.
B4X:
Dim thumb As Thumbnailator
Dim PreviewBytesJpg() As Byte
Dim PreviewBytesPng() As Byte
'This creates a thumbnail of 250px wide, the height is zero which means it will auto calculate based on the aspect of the image
PreviewBytesJpg= thumb.CreateThumbnail(ResultBytes,250,0) 'Returns a JPEG
PreviewBytesPng= thumb.CreateThumbnail2(ResultBytes,250,0) 'Returns a PNG which can be transparent
Alexander, let me know if you need any other methods exposed in the wrapper. I only exposed those two for my needs as I was converting the bytes to a base64 image and not writing to disk.
Alexander, let me know if you need any other methods exposed in the wrapper. I only exposed those two for my needs as I was converting the bytes to a base64 image and not writing to disk.
javac 1.8.0_191
src\net\myproject\api\my_handler.java:410: error: cannot access ThumbnailatorWrapper
nz.ope.thumbnailator.ThumbnailatorWrapper _thumb = null;
^
bad class file: D:\OneDrive\B4X Libs\b4j\thumbnailator.jar(nz/ope/thumbnailator/ThumbnailatorWrapper.class)
class file has wrong version 55.0, should be 52.0
Please remove or make sure it appears in the correct subdirectory of the classpath.
1 error
The library already has nice functions, I would do it too if I knew how.
Your'e right, but now i need this library, because on java 11 i cant use jFX in a non-ui project.
But the thumbnail creation works very well, the images that were 50kb in size by my old function are now 10kb in size, because I don't divide the normal size by 2 anymore.
Alexander, let me know if you need any other methods exposed in the wrapper. I only exposed those two for my needs as I was converting the bytes to a base64 image and not writing to disk.