[英]Pixel access of BufferedImage - memory leak?
我想從多個圖像構建直方圖。 為了執行此過程,我可以訪問DataBufferByte
我知道在構建直方圖后GC不會釋放內存。 此代碼有什么問題?
import java.awt.Color;
import java.awt.image.BufferedImage;
import java.awt.image.DataBufferByte;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map.Entry;
import java.util.concurrent.atomic.AtomicInteger;
import javax.imageio.ImageIO;
public class Histogram {
HashMap<Color,AtomicInteger> histogram;
public Histogram() {
histogram = new HashMap<>();
}
public void build(BufferedImage image){
int pixelLength = 3;
byte[] pixels = ((DataBufferByte) image.getRaster().getDataBuffer()).getData();
int red, green, blue;
Color color;
for ( int pixel = 0; pixel <= pixels.length - pixelLength; pixel+= pixelLength ) {
blue= ((int) pixels[pixel] & 0xff); // blue
green= (((int) pixels[pixel + 1] & 0xff) ); // green
red = (((int) pixels[pixel + 2] & 0xff) ); // red
color = new Color(red, green, blue);
if(histogram.containsKey(color)){
histogram.get(color).incrementAndGet();
}
else{
histogram.put(color, new AtomicInteger(1));
}
}
pixels = null;
}
public static void main(String[] args) {
String pathImage = "C://testjpg";
try {
for (int j = 0; j < 5000; j++) {
BufferedImage i = ImageIO.read(new File(pathImage));
Histogram h = new Histogram();
h.build(i);
i.flush();
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
謝謝你的支持 :)
GC不會自動運行,僅在需要時才調用內存。 您可以使用System.gc()強制執行此操作,但請注意不要經常執行此操作,否則會減慢程序速度。
您的代碼運行良好,這是我測試過的內容:
public static void buildColorHistogram(BufferedImage image)
{
final int pixelLength = 3;
byte[] pixels = ((DataBufferByte) image.getRaster().getDataBuffer()).getData();
for (int pixel=0 ; pixel < pixels.length; pixel+=pixelLength)
{
final int blue = pixels[pixel] & 0xff ; // blue
final int green= pixels[pixel + 1] & 0xff ; // green
final int red = pixels[pixel + 2] & 0xff ; // red
Color color = new Color(red, green, blue) ;
if ( histogram.containsKey(color) )
histogram.get(color).incrementAndGet() ;
else
histogram.put(color, new AtomicInteger(1)) ;
}
pixels = null ;
}
請注意,某些彩色圖像也具有Alpha通道,這意味着pixelLength
將為4而不是3。
完成處理后,是否清空(刷新)直方圖? 因為有1600萬種顏色的組合/三元組。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.