double xScale;
double yScale;
AffineTransform transform;
AffineTransformOp scale;
if (type > AffineTransformOp.TYPE_NEAREST_NEIGHBOR) {
// Initially scale so all remaining operations will halve the image
if ((width < input.getWidth()) || (height < input.getHeight())) {
int w = width;
int h = height;
while (w < (input.getWidth() / 2)) {
w *= 2;
}
while (h < (input.getHeight() / 2)) {
h *= 2;
}
xScale = w / (double)input.getWidth();
yScale = h / (double)input.getHeight();
//System.out.println("First scale by x=" + xScale + ", y=" + yScale);
transform = AffineTransform.getScaleInstance(xScale, yScale);
scale = new AffineTransformOp(transform, AffineTransformOp.TYPE_BILINEAR);
temp = scale.filter(temp, null);
}
}
scale = null; // NOTE: This resets!
xScale = width / (double)temp.getWidth();
yScale = height / (double)temp.getHeight();
if (type > AffineTransformOp.TYPE_NEAREST_NEIGHBOR) {
// TODO: Test skipping first scale (above), and instead scale once
// more here, and a little less than .5 each time...
// That would probably make the scaling smoother...
while ((xScale < 0.5) || (yScale < 0.5)) {
if (xScale >= 0.5) {
//System.out.println("Halving by y=" + (yScale * 2.0));
transform = AffineTransform.getScaleInstance(1.0, 0.5);
scale = new AffineTransformOp(transform, AffineTransformOp.TYPE_BILINEAR);
yScale *= 2.0;
} else if (yScale >= 0.5) {
//System.out.println("Halving by x=" + (xScale * 2.0));
transform = AffineTransform.getScaleInstance(0.5, 1.0);
scale = new AffineTransformOp(transform, AffineTransformOp.TYPE_BILINEAR);
xScale *= 2.0;
} else {
//System.out.println("Halving by x=" + (xScale * 2.0) + ", y=" + (yScale * 2.0));
xScale *= 2.0;
yScale *= 2.0;
}
if (scale == null) {
transform = AffineTransform.getScaleInstance(0.5, 0.5);
scale = new AffineTransformOp(transform, AffineTransformOp.TYPE_BILINEAR);
}
temp = scale.filter(temp, null);
}
}
//System.out.println("Rest to scale by x=" + xScale + ", y=" + yScale);
transform = AffineTransform.getScaleInstance(xScale, yScale);
scale = new AffineTransformOp(transform, type);
return scale.filter(temp, output);
}