All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends Macros Modules Pages
SVImageHandler.java
Go to the documentation of this file.
1 // Copyright 2007 Google Inc. All Rights Reserved.
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License"); You may not
4 // use this file except in compliance with the License. You may obtain a copy of
5 // the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by
6 // applicable law or agreed to in writing, software distributed under the
7 // License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS
8 // OF ANY KIND, either express or implied. See the License for the specific
9 // language governing permissions and limitations under the License.
10 
11 package com.google.scrollview.ui;
12 
13 import org.piccolo2d.nodes.PImage;
14 
15 import java.io.BufferedReader;
16 import java.io.ByteArrayInputStream;
17 import java.io.IOException;
18 import javax.imageio.ImageIO;
19 import javax.xml.bind.DatatypeConverter;
20 
29 public class SVImageHandler {
30  /* All methods are static, so we forbid to construct SVImageHandler objects */
31  private SVImageHandler() {
32  }
33 
42  public static PImage readImage(int size, BufferedReader in) {
43  char[] charbuffer = new char[size];
44  int numRead = 0;
45  while (numRead < size) {
46  int newRead = -1;
47  try {
48  newRead = in.read(charbuffer, numRead, size - numRead);
49  } catch (IOException e) {
50  System.out.println("Failed to read image data from socket:" + e.getMessage());
51  return null;
52  }
53  if (newRead < 0) {
54  return null;
55  }
56  numRead += newRead;
57  }
58  if (numRead != size) {
59  System.out.println("Failed to read image data from socket");
60  return null;
61  }
62  // Convert the character data to binary.
63  byte[] binarydata = DatatypeConverter.parseBase64Binary(new String(charbuffer));
64  // Convert the binary data to a byte stream and parse to image.
65  ByteArrayInputStream byteStream = new ByteArrayInputStream(binarydata);
66  try {
67  PImage img = new PImage(ImageIO.read(byteStream));
68  return img;
69  } catch (IOException e) {
70  System.out.println("Failed to decode image data from socket" + e.getMessage());
71  }
72  return null;
73  }
74 }
static PImage readImage(int size, BufferedReader in)