Skip to content

Instantly share code, notes, and snippets.

@jashatton
Created December 23, 2013 18:15
Show Gist options
  • Save jashatton/8102019 to your computer and use it in GitHub Desktop.
Save jashatton/8102019 to your computer and use it in GitHub Desktop.
A class that can create a circle as a png and reencode it as a dataurl, Base64 encoded, image. I used this to create markers on Google Maps in GWT.
import java.awt.AlphaComposite;
import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.image.BufferedImage;
import java.awt.image.RenderedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import javax.imageio.ImageIO;
import org.apache.commons.codec.binary.Base64;
public class PngToDataUrl {
// gets the created marker image and Base64 encodes it into a String. The
// Base64 class is from Apache commons codec project.
public String createEncodedMarkerIcon(int markerSize) {
byte[] markerImage = getMarkerImage(markerSize);
String encodedMarkerImage = Base64.encodeBase64String(markerImage);
return encodedMarkerImage;
}
// this creates a PNG using the RenderedImage created by the createImage
// method.
private byte[] getMarkerImage(int size) {
ByteArrayOutputStream byteOutputStream = new ByteArrayOutputStream();
try {
ImageIO.write(createImage(size), "PNG", byteOutputStream);
} catch (IOException e) {
e.printStackTrace();
}
return byteOutputStream.toByteArray();
}
// Returns a generated image using Graphics2D
private RenderedImage createImage(int size) {
int width = size;
int height = size;
BufferedImage bufferedImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
// Create a graphics contents on the buffered image
Graphics2D g2d = bufferedImage.createGraphics();
g2d.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER));
g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
g2d.setBackground(new Color(0, 0, 0, 0));
g2d.setPaint(new Color(1.0f, 0, 0, 1.0f));
g2d.fillOval(0, 0, width, height);
// Graphics context no longer needed so dispose it
g2d.dispose();
return bufferedImage;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment