Skip to content

Instantly share code, notes, and snippets.

@jaggedprospect
Last active June 1, 2022 23:57
Show Gist options
  • Save jaggedprospect/4f8a7a939f74895507f7cba8c4281662 to your computer and use it in GitHub Desktop.
Save jaggedprospect/4f8a7a939f74895507f7cba8c4281662 to your computer and use it in GitHub Desktop.
Alternate Image class constructor that implements scaling. (For use in the 2D Java Game Engine series by Majoolwip)
//<insert_package_declaration>
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.IOException;
public class Image {
private int width, height;
private int[] pixels;
private boolean alpha = false;
public Image(String path, float scale){
BufferedImage image = null;
// Read file at path
try {
image = ImageIO.read(Image.class.getResourceAsStream(path));
} catch (IOException e) {
e.printStackTrace();
}
// Scale dimensions
width = (int)(image.getWidth() * scale);
height = (int)(image.getHeight() * scale);
// Resize image to scaled dimensions
BufferedImage scaledImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
Graphics2D g2d = scaledImage.createGraphics();
g2d.drawImage(image, 0, 0, width, height, null);
g2d.dispose();
// Save image pixel data to array
pixels = scaledImage.getRGB(0,0, width, height, null, 0, width);
image.flush();
}
}
@jaggedprospect
Copy link
Author

jaggedprospect commented Jun 1, 2022

I used this as a secondary constructor in my project to avoid the hassle of passing 1f when instantiating an Image with it's native resolution, but you could use it as the primary constructor method.

Follow Majoolwip's full 2D Java Game Engine tutorial here!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment