Jump to content
  • Advertisement
Sign in to follow this  
VildNinja

[java] My texture loader code is ugly!

This topic is 3157 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

Hey I've written my own texture loader for lwjgl. It works perfectly well, but I really don't like it :/ so does any of you guys know a better way to load an image, and save it into an int array (or a ByteByffer), without using any libraries other than whats in the jre, and without I need to write loaders for the specific file types? the part of the code, that I would like to rewrite:
Image img = Toolkit.getDefaultToolkit().getImage(path);

// make sure to load the image before continuing
// necessary for remote images
MediaTracker mt = new MediaTracker(new Panel());
mt.addImage(img, 1);
try {
	mt.waitForID(1);
} catch (InterruptedException ex) {
	Log.error(path.toString() + " could not be loaded");
}

// get the nearest power of two values
int width = powerOfTwo(img.getWidth(null));
int height = powerOfTwo(img.getHeight(null));

BufferedImage bimg = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);

// this is the part i really don't like!
// isn't there an other way to go from Image to int array?
bimg.getGraphics().drawImage(img, 0, height - img.getHeight(null), null);
int[] rgbaArray = new int[width * height];
bimg.getRGB(0, 0, width, height, rgbaArray, 0, width);

hope anyone can help :)

Share this post


Link to post
Share on other sites
Advertisement
You can use a PixelGrabber to get the int[] image data from an Image:

Image img = Toolkit.getDefaultToolkit().getImage(path);

PixelGrabber pg = new PixelGrabber(img, 0, 0, -1, -1, true);
if(!pg.grabPixels()) {
// Handle error here
}

int[] imgData = (int[])pg.getPixels();



Or, use the ImageIO class, which returns a BufferedImage directly:

BufferedImage img = ImageIO.read(new File(path));
int[] imgData = img2.getRGB(0, 0, img.getWidth(null), img.getHeight(null), null, 0, img.getWidth(null));

Share this post


Link to post
Share on other sites
Quote:
Original post by mattd
Or, use the ImageIO class, which returns a BufferedImage directly:
*** Source Snippet Removed ***


Ooo, that's a lot more efficient than what I used to use (which was similar to the OP's original technique)... I'll have to remember that for my next Java project(s).

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

Participate in the game development conversation and more when you create an account on GameDev.net!

Sign me up!