
Il y a une solution triviale - pour analyser chaque pixel. L'algorithme ci-dessous a des performances constantes O(w•h)
.
private static BufferedImage trimImage(BufferedImage image) {
int width = image.getWidth();
int height = image.getHeight();
int top = height/2;
int bottom = top;
int left = width/2 ;
int right = left;
for (int x = 0; x < width; x++) {
for (int y = 0; y < height; y++) {
if (image.getRGB(x, y) != 0){
top = Math.min(top, x);
bottom = Math.max(bottom, x);
left = Math.min(left, x);
right = Math.max(right, x);
}
}
}
return image.getSubimage(left, top, right - left, bottom - top);
}
Mais ce qui est beaucoup plus efficace:
private static BufferedImage trimImage(BufferedImage image) {
WritableRaster raster = image.getAlphaRaster();
int width = raster.getWidth();
int height = raster.getHeight();
int left = 0;
int top = 0;
int right = width - 1;
int bottom = height - 1;
int minRight = width - 1;
int minBottom = height - 1;
top:
for (;top < bottom; top++){
for (int x = 0; x < width; x++){
if (raster.getSample(x, top, 0) != 0){
minRight = x;
minBottom = top;
break top;
}
}
}
left:
for (;left < minRight; left++){
for (int y = height - 1; y > top; y--){
if (raster.getSample(left, y, 0) != 0){
minBottom = y;
break left;
}
}
}
bottom:
for (;bottom > minBottom; bottom--){
for (int x = width - 1; x >= left; x--){
if (raster.getSample(x, bottom, 0) != 0){
minRight = x;
break bottom;
}
}
}
right:
for (;right > minRight; right--){
for (int y = bottom; y >= top; y--){
if (raster.getSample(right, y, 0) != 0){
break right;
}
}
}
return image.getSubimage(left, top, right - left + 1, bottom - top + 1);
}
Cet algorithme suit la réponse de l'idée de Pepan (voir ci-dessus) et est 2 à 4 fois plus efficace. La différence est la suivante: il ne scanne jamais un pixel deux fois et essaie de contracter la plage de recherche sur chaque étape.
performance de la méthode dans le pire des cas est O(w•h–a•b)
Oui, je suis au courant de quelque chose comme une étoile, pas beaucoup de redimensionnement. J'espérais qu'il y avait une sorte de filtre intégré. – Ruggs