Search code examples
javaimagepixelmemoryimagesource

How to expand an image with MemoryImageSource?


I got a byte[] getting from a file, and I want to display the associated image, I found :

// p.data is a byte[]
int[] pixels = new int[p.width * p.height];
for (int i = 0; i < pixels.length; i++) {
   pixels[i] = 0xFF000000 + intValue(p.data[i]) * 0x010101;
}
MemoryImageSource source = new MemoryImageSource(p.width, p.height, pixels, 0, p.width );
Image img = Toolkit.getDefaultToolkit().createImage(source);

//intValue is just : intValue(byte b) { return b < 0 ? b + 256 : b;}
  

That show :

enter image description here


And i would like to have twice bigger (width and height), I tried :

int[] pixels = new int[p.width * p.height *4];
for (int i = 0; i < pixels.length; i++) {
   pixels[i] = 0xFF000000 + BytePixmap.intValue(p.data[i/4]) * 0x010101;
}
MemoryImageSource source = new MemoryImageSource(p.width*2,p.height*2, pixels, 0, p.width);

I got :

enter image description here and enter image description here

if I change p.width to p.width*2 (last param)

I can't figure how to keep an 8*8 square picture


EDIT :

An example can be found here : Working example , it cannot be run on Ideone sure because it requires a display, but it works


Solution

  • Resize the image after you have loaded it. That way you can use all of the tools available in the java2d api.

    BufferedImage scaled = new BufferedImage(p.width*2,p.height*2, BufferedImage.TYPE_INT_ARGB);
    Graphics2D g = (Graphics2D)scaled.getGraphics();
    g.drawImage(img, AffineTransform.getScaleInstance(2,2), null);
    g.dispose();
    

    Now scaled has an image 2x the size. You could even do this in the display you're using.

    Another way, if you just want a scaled instanced, then you can use Image#getScaledInstance.