Last active
June 1, 2022 23:57
-
-
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)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//<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(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I used this as a secondary constructor in my project to avoid the hassle of passing
1f
when instantiating anImage
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!