I have looked at these post How to resize an image without loading into memory? and JMACKIG https://github.com/justinedelson/jmagick only runs on linux and im on a windows currently or has not been tested on onther operating systems besided linux is notes in the README.md Also have looked at this post Java image scaling without loading the whole image into memory But in this case he get the image from a File in mine case I get the image from a Image
object.
The use case in mine case is that mine program is in a while loop and then takes screenshots. Then the program looks at the image to detect color and determain where ever it has to do some action based on the color it finds. But the problem right now is that after about 60 iterations of the loop I get a memory leak with this error java get out of memory heap space
So I also tried to clear up mine java cache after every iterations with this bat file: Clear Java Cache but thats seems to do about nothing
So is there anyway that its possible to clear the cache after every iteration of the loop or in the resize function clear the cache of make that the image doesnt go into the cache? Also have seen post where you can increase the max cache size of the program but that doesnt really fix the problem in this case cause The program runs doubtly longer but the error will still occurr and I want to find a way to make it possible that I dont get that memory leak at all.
the code for the image resizing
public Image SCapture(int w, int h) throws Exception
{
Robot robot = new Robot();
BufferedImage screenCapture = robot.createScreenCapture(new Rectangle(Toolkit.getDefaultToolkit().getScreenSize()));
Image image = getScaledImage(screenCapture, w, h);
return image;
}
//Gets screen width and height from main
private static Image getScaledImage(Image srcImg, int w, int h){
BufferedImage resizedImg = new BufferedImage(w, h, BufferedImage.TYPE_INT_ARGB);
Graphics2D g2 = resizedImg.createGraphics();
g2.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
g2.drawImage(srcImg, 0, 0, w, h, null);
g2.dispose();
return resizedImg;
}
Also I dont really care about image quality it just has to be done fast and clean
Update: After looking in the code more it was something with mine ArrayList checking all the color of the pixels. But this little trick at the end of mine while loop solved the problem
How to force garbage collection in Java?
public static void gc() {
Object obj = new Object();
WeakReference ref = new WeakReference<Object>(obj);
obj = null;
while(ref.get() != null) {
System.gc();
}
}