Java: Image conversion to byte[] array

Convertire un byte array (byte[]) in un oggetto Image e’ molto semplice:

	private Image convertToImage(byte[] source){
	Image objImage = new Image(source);
	return objImage;
}

Il contrario invece, convertire un oggetto Image in un byte[] non e’ proprio cosi’ immediaito. Ecco lo snippet che uso, che carica direttamente da una URL un’immagine e la memorizza in un byte[]. comodo magari da usare successivamente all’interno degli elementi di una jList.

private byte[] loadImageFromURL(String strUrl){
	int intPos;
	String strFileExt;

	//guess file extension
	intPos = strUrl.lastIndexOf(".");
	if (intPos >= 0){
		strFileExt = strUrl.substring(intPos + 1);
	}else{
		//assign default jpg extension
		strFileExt = "jpg";
	}

	try {
		//load the image from the Internet
		ImageIcon objImageIcon = new ImageIcon(new URL(strUrl));

		//wait the loading of the image
		MediaTracker objMediaTracker = new MediaTracker(lstContacts);
		objMediaTracker.addImage(objImageIcon.getImage(), 0);
		objMediaTracker.waitForID(0, 5000);

		//convert the image
		BufferedImage objBI = new BufferedImage(objImageIcon.getIconWidth(), objImageIcon.getIconHeight(), BufferedImage.TYPE_INT_ARGB);
		Graphics2D g2 = objBI.createGraphics();
		g2.drawImage(objImageIcon.getImage(), 0, 0, null);
		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		ImageIO.write(objBI, strFileExt, baos);

		return baos.toByteArray();

	} catch (MalformedURLException ex) {
		Logger.getLogger(MainForm.class.getName()).log(Level.SEVERE, null, ex);
		return null;
	} catch (IOException ex) {
		Logger.getLogger(MainForm.class.getName()).log(Level.SEVERE, null, ex);
		return null;
	} catch (InterruptedException ex) {
		Logger.getLogger(MainForm.class.getName()).log(Level.SEVERE, null, ex);
		return null;
	}
}

Continue reading “Java: Image conversion to byte[] array”