/alaspatial/src/main/java/org/ala/spatial/util/WrapBufferedImage.java

http://alageospatialportal.googlecode.com/ · Java · 74 lines · 58 code · 12 blank · 4 comment · 5 complexity · 8e00cf320b3d1a474092a3e3022321d7 MD5 · raw file

  1. package org.ala.spatial.util;
  2. import java.awt.image.BufferedImage;
  3. import java.io.ByteArrayInputStream;
  4. import java.io.ByteArrayOutputStream;
  5. import java.io.IOException;
  6. import java.io.Serializable;
  7. import javax.imageio.ImageIO;
  8. /**
  9. *
  10. * @author ajay
  11. */
  12. public class WrapBufferedImage implements Serializable {
  13. static final long serialVersionUID = 6583156430853699407L;
  14. private BufferedImage im = null;
  15. public WrapBufferedImage() {
  16. super();
  17. }
  18. public BufferedImage getIm() {
  19. return im;
  20. }
  21. public void setIm(BufferedImage im) {
  22. this.im = im;
  23. }
  24. private BufferedImage fromByteArray(byte[] imagebytes) {
  25. try {
  26. if (imagebytes != null && (imagebytes.length > 0)) {
  27. BufferedImage im = ImageIO.read(new ByteArrayInputStream(imagebytes));
  28. return im;
  29. }
  30. return null;
  31. } catch (IOException e) {
  32. throw new IllegalArgumentException(e.toString());
  33. }
  34. }
  35. private byte[] toByteArray(BufferedImage o) {
  36. if (o != null) {
  37. BufferedImage image = (BufferedImage) o;
  38. ByteArrayOutputStream baos = new ByteArrayOutputStream(1024);
  39. try {
  40. ImageIO.write(image, "png", baos);
  41. } catch (IOException e) {
  42. throw new IllegalStateException(e.toString());
  43. }
  44. byte[] b = baos.toByteArray();
  45. return b;
  46. }
  47. return new byte[0];
  48. }
  49. private void writeObject(java.io.ObjectOutputStream out)
  50. throws IOException {
  51. byte[] b = toByteArray(im);
  52. out.writeInt(b.length);
  53. out.write(b);
  54. }
  55. private void readObject(java.io.ObjectInputStream in)
  56. throws IOException, ClassNotFoundException {
  57. int length = in.readInt();
  58. byte[] b = new byte[length];
  59. in.read(b);
  60. im = fromByteArray(b);
  61. }
  62. }