Java Code Examples for javax.imageio.ImageIO

The following code examples are extracted from open source projects. You can click to vote up the examples that are useful to you.

Example 1

From project activiti-explorer, under directory /src/main/java/org/activiti/explorer/util/.

Source file: ImageUtil.java

  18 
vote

/** 
 * Resizes the given image (passed as  {@link InputStream}. If the image is smaller then the given maximum width or height, the image will be proportionally resized.
 */
public static InputStream smallify(InputStream imageInputStream,String mimeType,int maxWidth,int maxHeight){
  try {
    BufferedImage image=ImageIO.read(imageInputStream);
    int width=Math.min(image.getWidth(),maxWidth);
    int height=Math.min(image.getHeight(),maxHeight);
    Mode mode=Mode.AUTOMATIC;
    if (image.getHeight() > maxHeight) {
      mode=Mode.FIT_TO_HEIGHT;
    }
    if (width != image.getWidth() || height != image.getHeight()) {
      image=Scalr.resize(image,mode,width,height);
    }
    ByteArrayOutputStream bos=new ByteArrayOutputStream();
    ImageIO.write(image,Constants.MIMETYPE_EXTENSION_MAPPING.get(mimeType),bos);
    return new ByteArrayInputStream(bos.toByteArray());
  }
 catch (  IOException e) {
    LOGGER.log(Level.SEVERE,"Exception while resizing image",e);
    return null;
  }
}
 

Example 2

From project 16Blocks, under directory /src/main/java/de/minestar/sixteenblocks/Number/.

Source file: NumberUnit.java

  16 
vote

private void loadFromBitmap(){
  try {
    BufferedImage img=ImageIO.read(new File(Core.getInstance().getDataFolder(),"numbers.png"));
    int startX=this.number * 7;
    Color thisColor;
    int thisWidth=0;
    for (int y=0; y < img.getHeight(); y++) {
      int nowX=0;
      for (int x=startX; x < startX + 7; x++) {
        thisColor=new Color(img.getRGB(x,y));
        if (y == 0) {
          if (thisColor.getRed() != 255) {
            thisWidth++;
          }
        }
        if (thisColor.getGreen() == 255) {
          this.addBlock(-nowX,img.getHeight() - y - 1,35,(byte)15);
        }
 else         if (thisColor.getBlue() == 255) {
          this.addBlock(-nowX,img.getHeight() - y - 1,35,(byte)8);
        }
        nowX++;
        if (thisColor.getRed() == 255) {
          nowX--;
        }
      }
    }
    this.setWidth(thisWidth);
  }
 catch (  Exception e) {
    e.printStackTrace();
  }
}
 

Example 3

From project ajah, under directory /ajah-image/src/main/java/com/ajah/image/.

Source file: AutoCrop.java

  15 
vote

/** 
 * Crops an image based on the value of the top left pixel.
 * @param data The image data.
 * @param fuzziness The fuzziness allowed for minor deviations (~5 is recommended).
 * @return The new image data, cropped.
 * @throws IOException If the image could not be read.
 */
public static byte[] autoCrop(final byte[] data,final int fuzziness) throws IOException {
  final BufferedImage image=ImageIO.read(new ByteArrayInputStream(data));
  final BufferedImage cropped=autoCrop(image,fuzziness);
  final ByteArrayOutputStream out=new ByteArrayOutputStream();
  ImageIO.write(cropped,"png",out);
  return out.toByteArray();
}
 

Example 4

From project android-joedayz, under directory /Proyectos/spring-rest-servidor/src/main/java/com/mycompany/rest/controller/.

Source file: PersonController.java

  15 
vote

@RequestMapping(value="/person/{id}",method=RequestMethod.GET,headers="Accept=image/jpeg, image/jpg, image/png, image/gif") public @ResponseBody byte[] getPhoto(@PathVariable("id") Long id){
  try {
    InputStream is=this.getClass().getResourceAsStream("/bella.jpg");
    BufferedImage img=ImageIO.read(is);
    ByteArrayOutputStream bao=new ByteArrayOutputStream();
    ImageIO.write(img,"jpg",bao);
    logger.debug("Retrieving photo as byte array image");
    return bao.toByteArray();
  }
 catch (  IOException e) {
    logger.error(e);
    throw new RuntimeException(e);
  }
}
 

Example 5

From project ANNIS, under directory /annis-gui/src/main/java/annis/gui/visualizers/iframe/tree/.

Source file: TigerTreeVisualizer.java

  15 
vote

@Override public void writeOutput(VisualizerInput input,OutputStream outstream){
  this.input=input;
  AnnisResult result=input.getResult();
  List<AbstractImageGraphicsItem> layouts=new LinkedList<AbstractImageGraphicsItem>();
  double width=0;
  double maxheight=0;
  for (  DirectedGraph<AnnisNode,Edge> g : graphtools.getSyntaxGraphs(input)) {
    ConstituentLayouter<AbstractImageGraphicsItem> cl=new ConstituentLayouter<AbstractImageGraphicsItem>(g,backend,labeler,styler,input);
    AbstractImageGraphicsItem item=cl.createLayout(new LayoutOptions(VerticalOrientation.TOP_ROOT,AnnisGraphTools.detectLayoutDirection(result.getGraph())));
    Rectangle2D treeSize=item.getBounds();
    maxheight=Math.max(maxheight,treeSize.getHeight());
    width+=treeSize.getWidth();
    layouts.add(item);
  }
  BufferedImage image=new BufferedImage((int)(width + (layouts.size() - 1) * TREE_DISTANCE + 2 * SIDE_MARGIN),(int)(maxheight + 2 * TOP_MARGIN),BufferedImage.TYPE_INT_ARGB);
  Graphics2D canvas=createCanvas(image);
  double xOffset=SIDE_MARGIN;
  for (  AbstractImageGraphicsItem item : layouts) {
    AffineTransform t=canvas.getTransform();
    Rectangle2D bounds=item.getBounds();
    canvas.translate(xOffset,TOP_MARGIN + maxheight - bounds.getHeight());
    renderTree(item,canvas);
    xOffset+=bounds.getWidth() + TREE_DISTANCE;
    canvas.setTransform(t);
  }
  try {
    ImageIO.write(image,"png",outstream);
  }
 catch (  IOException e) {
    throw new RuntimeException(e);
  }
}
 

Example 6

From project aranea, under directory /core/src/main/java/no/dusken/aranea/service/.

Source file: StoreImageServiceImpl.java

  15 
vote

public Image changeImage(File file,Image image) throws IOException {
  String hash=MD5.asHex(MD5.getHash(file));
  if (isBlank(hash)) {
    throw new IOException("Could not get hash from " + file.getAbsolutePath());
  }
  Image existingImage=imageService.getImageByHash(hash);
  if (existingImage != null) {
    log.info("Imported existing Image: {} from the user",existingImage.toString());
    file.delete();
    return existingImage;
  }
 else {
    image.setHash(hash);
    BufferedImage rendImage=ImageIO.read(file);
    image.setHeight(rendImage.getHeight());
    image.setWidth(rendImage.getWidth());
    image.setFileSize(file.length());
    FileUtils.copyFile(file,new File(imageDirectory + "/" + image.getUrl()));
    file.delete();
    log.debug("Imported Image: {} from {}",image.toString(),file.getAbsolutePath());
    return imageService.saveOrUpdate(image);
  }
}
 

Example 7

From project arquillian-graphene, under directory /graphene-selenium/graphene-selenium-impl/src/main/java/org/jboss/arquillian/ajocado/framework/.

Source file: TypedSeleniumImpl.java

  15 
vote

private BufferedImage decodeBase64Screenshot(String screenshotInBase64){
  byte[] screenshotPng=Base64.decodeBase64(screenshotInBase64);
  ByteArrayInputStream inputStream=new ByteArrayInputStream(screenshotPng);
  BufferedImage result;
  try {
    result=ImageIO.read(inputStream);
  }
 catch (  IOException e) {
    throw new RuntimeException(e);
  }
  return result;
}
 

Example 8

From project arquillian-rusheye, under directory /rusheye-impl/src/main/java/org/jboss/rusheye/.

Source file: CommandCompare.java

  15 
vote

public void writeDifferenceImage(){
  try {
    ImageIO.write(result.getDiffImage(),"PNG",output);
  }
 catch (  Exception e) {
    printErrorMessage(e);
    System.exit(3);
  }
}
 

Example 9

From project autopsy, under directory /Core/src/org/sleuthkit/autopsy/corecomponents/.

Source file: DataContentViewerPicture.java

  15 
vote

@Override public void setNode(Node selectedNode){
  this.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
  try {
    if (selectedNode != null) {
      try {
        Content content=selectedNode.getLookup().lookup(Content.class);
        byte[] dataSource=new byte[(int)content.getSize()];
        int bytesRead=content.read(dataSource,0,content.getSize());
        if (bytesRead > 0) {
          InputStream is=new ByteArrayInputStream(dataSource);
          Image image=ImageIO.read(is);
          if (image != null)           this.picLabel.setIcon(new javax.swing.ImageIcon(image));
        }
      }
 catch (      TskException ex) {
        Logger.getLogger(this.className).log(Level.WARNING,"Error while trying to display the picture content.",ex);
      }
catch (      Exception ex) {
        Logger.getLogger(this.className).log(Level.WARNING,"Error while trying to display the picture content.",ex);
      }
    }
  }
  finally {
    this.setCursor(null);
  }
}
 

Example 10

From project b3log-latke, under directory /latke/src/main/java/org/b3log/latke/image/local/.

Source file: LocalImageService.java

  15 
vote

@Override public Image makeImage(final List<Image> images){
  if (null == images || images.isEmpty()) {
    return null;
  }
  try {
    final Image firstImage=images.get(0);
    BufferedImage tmp=ImageIO.read(new ByteArrayInputStream(firstImage.getData()));
    for (int i=1; i < images.size(); i++) {
      final Image image=images.get(i);
      final byte[] data=image.getData();
      final BufferedImage awtImage=ImageIO.read(new ByteArrayInputStream(data));
      tmp=splice(tmp,awtImage);
    }
    final Image ret=new Image();
    final ByteArrayOutputStream byteArrayOutputStream=new ByteArrayOutputStream();
    ImageIO.write(tmp,"PNG",byteArrayOutputStream);
    final byte[] data=byteArrayOutputStream.toByteArray();
    ret.setData(data);
    return ret;
  }
 catch (  final IOException e) {
    throw new RuntimeException(e);
  }
}
 

Example 11

From project BioMAV, under directory /Behavior/src/nl/ru/ai/projects/parrot/tools/.

Source file: TwitterAccess.java

  15 
vote

/** 
 * Uploads an image
 * @param image The image to upload
 * @param tweet The text of the tweet that needs to be posted with the image
 */
public void uploadImage(byte[] image,String tweet){
  if (!enabled)   return;
  ByteArrayOutputStream baos=new ByteArrayOutputStream();
  RenderedImage img=getImageFromCamera(image);
  try {
    ImageIO.write(img,"jpg",baos);
    URL url=new URL("http://api.imgur.com/2/upload.json");
    String data=URLEncoder.encode("image","UTF-8") + "=" + URLEncoder.encode(Base64.encodeBase64String(baos.toByteArray()),"UTF-8");
    data+="&" + URLEncoder.encode("key","UTF-8") + "="+ URLEncoder.encode("f9c4861fc0aec595e4a64dd185751d28","UTF-8");
    URLConnection conn=url.openConnection();
    conn.setDoOutput(true);
    OutputStreamWriter wr=new OutputStreamWriter(conn.getOutputStream());
    wr.write(data);
    wr.flush();
    StringBuffer buffer=new StringBuffer();
    InputStreamReader isr=new InputStreamReader(conn.getInputStream());
    Reader in=new BufferedReader(isr);
    int ch;
    while ((ch=in.read()) > -1)     buffer.append((char)ch);
    String imgURL=processJSON(buffer.toString());
    setStatus(tweet + " " + imgURL,100);
  }
 catch (  IOException e1) {
    e1.printStackTrace();
  }
}
 

Example 12

From project blogs, under directory /request-mappers/src/main/java/com/wicketinaction/requestmappers/resources/images/.

Source file: ImageResourceReference.java

  15 
vote

/** 
 * Generates an image with a label. For real life application this method will read the image bytes from  external source.
 * @param label the image text to render
 * @return
 */
private byte[] getImageAsBytes(String label){
  BufferedImage image=new BufferedImage(800,600,BufferedImage.TYPE_INT_RGB);
  Graphics2D g=(Graphics2D)image.getGraphics();
  g.setColor(Color.BLACK);
  g.setBackground(Color.WHITE);
  g.clearRect(0,0,image.getWidth(),image.getHeight());
  g.setFont(new Font("SansSerif",Font.PLAIN,48));
  g.drawString(label,50,50);
  g.dispose();
  Iterator<ImageWriter> writers=ImageIO.getImageWritersByFormatName("jpg");
  ImageWriter writer=writers.next();
  if (writer == null) {
    throw new RuntimeException("JPG not supported?!");
  }
  final ByteArrayOutputStream out=new ByteArrayOutputStream();
  byte[] imageBytes=null;
  try {
    ImageOutputStream imageOut=ImageIO.createImageOutputStream(out);
    writer.setOutput(imageOut);
    writer.write(image);
    imageOut.close();
    imageBytes=out.toByteArray();
  }
 catch (  IOException e) {
    e.printStackTrace();
  }
  return imageBytes;
}
 

Example 13

From project brut.apktool, under directory /apktool-lib/src/main/java/brut/androlib/res/decoder/.

Source file: Res9patchStreamDecoder.java

  15 
vote

public void decode(InputStream in,OutputStream out) throws AndrolibException {
  try {
    byte[] data=IOUtils.toByteArray(in);
    BufferedImage im=ImageIO.read(new ByteArrayInputStream(data));
    int w=im.getWidth(), h=im.getHeight();
    BufferedImage im2=new BufferedImage(w + 2,h + 2,BufferedImage.TYPE_4BYTE_ABGR);
    if (im.getType() == BufferedImage.TYPE_4BYTE_ABGR) {
      im2.getRaster().setRect(1,1,im.getRaster());
    }
 else {
      im2.getGraphics().drawImage(im,1,1,null);
    }
    NinePatch np=getNinePatch(data);
    drawHLine(im2,h + 1,np.padLeft + 1,w - np.padRight);
    drawVLine(im2,w + 1,np.padTop + 1,h - np.padBottom);
    int[] xDivs=np.xDivs;
    for (int i=0; i < xDivs.length; i+=2) {
      drawHLine(im2,0,xDivs[i] + 1,xDivs[i + 1]);
    }
    int[] yDivs=np.yDivs;
    for (int i=0; i < yDivs.length; i+=2) {
      drawVLine(im2,0,yDivs[i] + 1,yDivs[i + 1]);
    }
    ImageIO.write(im2,"png",out);
  }
 catch (  IOException ex) {
    throw new AndrolibException(ex);
  }
}
 

Example 14

From project capedwarf-blue, under directory /images/src/main/java/org/jboss/capedwarf/images/util/.

Source file: ImageUtils.java

  15 
vote

public static byte[] getByteArray(RenderedImage image,String formatName){
  try {
    ByteArrayOutputStream byteArrayOutputStream=new ByteArrayOutputStream();
    ImageIO.write(image,formatName,byteArrayOutputStream);
    return byteArrayOutputStream.toByteArray();
  }
 catch (  IOException e) {
    throw new RuntimeException(e);
  }
}
 

Example 15

From project Carolina-Digital-Repository, under directory /djatoka-cdr/src/gov/lanl/adore/djatoka/io/writer/.

Source file: PNGWriter.java

  15 
vote

/** 
 * Write a BufferedImage instance using implementation to the  provided OutputStream.
 * @param bi a BufferedImage instance to be serialized
 * @param os OutputStream to output the image to
 * @throws FormatIOException
 */
public void write(BufferedImage bi,OutputStream os) throws FormatIOException {
  if (bi != null) {
    BufferedOutputStream bos=null;
    try {
      bos=new BufferedOutputStream(os);
      ImageIO.write(bi,"png",bos);
    }
 catch (    IOException e) {
      logger.error(e,e);
    }
  }
}
 

Example 16

From project ceres, under directory /ceres-core/src/main/java/com/bc/ceres/core/runtime/internal/.

Source file: SplashScreenProgressMonitor.java

  15 
vote

private static BufferedImage loadImage(String imageFilePath){
  try {
    return ImageIO.read(new File(imageFilePath));
  }
 catch (  IOException e) {
    return null;
  }
}
 

Example 17

From project charts4j, under directory /src/test/java/com/googlecode/charts4j/example/.

Source file: SwingExample.java

  15 
vote

/** 
 * Display the chart in a swing window.
 * @param urlString the url string to display.
 * @throws IOException
 */
private static void displayUrlString(final String urlString) throws IOException {
  JFrame frame=new JFrame();
  JLabel label=new JLabel(new ImageIcon(ImageIO.read(new URL(urlString))));
  frame.getContentPane().add(label,BorderLayout.CENTER);
  frame.pack();
  frame.setVisible(true);
}
 

Example 18

From project Chess_1, under directory /src/chess/gui/.

Source file: ImageDisplay.java

  15 
vote

/** 
 * Constructs an object that knows how to display an image. Looks for the named file first in the jar file, then in the current directory.
 * @param imageFilename name of file containing image
 */
public ImageDisplay(Class cl) throws IOException {
  this.cl=cl;
  imageFilename=cl.getName().replace('.','/');
  URL url=cl.getClassLoader().getResource(imageFilename + imageExtension);
  if (url == null)   throw new FileNotFoundException(imageFilename + imageExtension + " not found.");
  tintedVersions.put("",ImageIO.read(url));
}
 

Example 19

From project ChkBugReport, under directory /src/com/sonyericsson/chkbugreport/plugins/logs/event/.

Source file: AMChart.java

  15 
vote

public String finish(Module br){
  if (mLastState != STATE_UNKNOWN) {
    drawState(W);
  }
  if (mUsed == 0) {
    return null;
  }
  String fn="amchart_" + hashCode() + ".png";
  try {
    ImageIO.write(mImg,"png",new File(br.getBaseDir() + fn));
  }
 catch (  IOException e) {
    e.printStackTrace();
  }
  return fn;
}
 

Example 20

From project chukwa, under directory /src/main/java/org/apache/hadoop/chukwa/hicc/.

Source file: ImageSlicer.java

  15 
vote

public BufferedImage prepare(String filename){
  try {
    src=ImageIO.read(new File(filename));
  }
 catch (  IOException e) {
    log.error("Image file does not exist:" + filename + ", can not render image.");
  }
  XYData fullSize=new XYData(1,1);
  while (fullSize.getX() < src.getWidth() || fullSize.getY() < src.getHeight()) {
    fullSize.set(fullSize.getX() * 2,fullSize.getY() * 2);
  }
  float scaleX=(float)fullSize.getX() / src.getWidth();
  float scaleY=(float)fullSize.getY() / src.getHeight();
  log.info("Image size: (" + src.getWidth() + ","+ src.getHeight()+ ")");
  log.info("Scale size: (" + scaleX + ","+ scaleY+ ")");
  AffineTransform at=AffineTransform.getScaleInstance(scaleX,scaleY);
  AffineTransformOp op=new AffineTransformOp(at,AffineTransformOp.TYPE_BILINEAR);
  BufferedImage dest=op.filter(src,null);
  return dest;
}
 

Example 21

From project CIShell, under directory /core/org.cishell.utilities/src/org/cishell/utilities/.

Source file: FileUtilities.java

  15 
vote

public static File writeBufferedImageIntoTemporaryDirectory(BufferedImage bufferedImage,String imageType) throws IOException, Exception {
  String temporaryDirectoryPath=getDefaultTemporaryDirectory();
  File temporaryImageFile=createTemporaryFileInTemporaryDirectory(temporaryDirectoryPath,"image-",imageType);
  if (!ImageIO.write(bufferedImage,imageType,temporaryImageFile)) {
    throw new Exception("No valid image writer was found for the image type " + imageType);
  }
  return temporaryImageFile;
}
 

Example 22

From project citrus-sample, under directory /archetype-webx-quickstart/src/main/resources/archetype-resources/src/main/java/app1/module/screen/simple/.

Source file: SayHiImage.java

  15 
vote

private void writeImage(OutputStream out) throws IOException {
  BufferedImage img=new BufferedImage(800,600,BufferedImage.TYPE_INT_RGB);
  Graphics2D g2d=img.createGraphics();
  g2d.setPaint(Color.red);
  g2d.setFont(new Font("Serif",Font.BOLD,36));
  g2d.drawString("Hi there, how are you doing today?",5,g2d.getFontMetrics().getHeight());
  g2d.dispose();
  ImageIO.write(img,"jpg",out);
}
 

Example 23

From project Clotho-Core, under directory /ClothoApps/WikiEditorPanel/src/org/clothocad/wikieditorpanel/.

Source file: WikiEditorPanel.java

  15 
vote

private void createEmptyHTMLPage(){
  File file=new File(Attachment.cacheDir.getAbsolutePath() + File.separator + "pencilandpaper.png");
  if (!file.exists()) {
    BufferedImage img=(BufferedImage)ImageUtilities.loadImage("org/clothocad/wikieditorpanel/pencilandpaper.png",false);
    if (img != null) {
      try {
        ImageIO.write(img,"png",file);
      }
 catch (      IOException ex) {
      }
    }
  }
  String imagelink=file.getAbsolutePath();
  JEditorPane pane=new JEditorPane("text/html","<html>\n<body>\n<p align=\"center\">&nbsp;</p>\n<p align=\"center\">&nbsp;</p>\n<p align=\"center\"><img src=\"file:\\" + File.separator + imagelink+ "\" width=\"110\" height=\"87\" alt=\"doubleClick\" /></p>\n<p align=\"center\">&nbsp;</p>\n<p align=\"center\" class=\"style1\">Double click to add text.</p>\n</body>\n</html>");
  pane.putClientProperty(JEditorPane.HONOR_DISPLAY_PROPERTIES,Boolean.TRUE);
  pane.setFont(new Font("Arial",Font.PLAIN,12));
  pane.setBackground(htmlEmpty);
  pane.setForeground(new Color(255,255,255));
  emptyHTMLPage=(HTMLDocument)pane.getDocument();
}
 

Example 24

From project core_4, under directory /impl/src/main/java/org/richfaces/application/.

Source file: InitializationListener.java

  15 
vote

public static void initialize(){
  if (!checkGetSystemClassLoaderAccess()) {
    LOGGER.warn("Access to system class loader restricted - AWTInitializer won't be run");
    return;
  }
  Thread thread=Thread.currentThread();
  ClassLoader initialTCCL=thread.getContextClassLoader();
  ImageInputStream testStream=null;
  try {
    ClassLoader systemCL=ClassLoader.getSystemClassLoader();
    thread.setContextClassLoader(systemCL);
    ImageIO.setUseCache(false);
    testStream=ImageIO.createImageInputStream(new ByteArrayInputStream(new byte[0]));
    Toolkit.getDefaultToolkit().getSystemEventQueue();
  }
 catch (  IOException e) {
    LOGGER.error(e.getMessage(),e);
  }
 finally {
    if (testStream != null) {
      try {
        testStream.close();
      }
 catch (      IOException e) {
        LOGGER.error(e.getMessage(),e);
      }
    }
    thread.setContextClassLoader(initialTCCL);
  }
}
 

Example 25

From project CraftMania, under directory /CraftMania/src/org/craftmania/game/.

Source file: TextureStorage.java

  15 
vote

public static Texture loadStichedTexture(String id,String resource0,String resource1) throws IOException {
  BufferedImage img0=ImageIO.read(getTextureFile(resource0));
  BufferedImage img1=ImageIO.read(getTextureFile(resource1));
  if (img0.getWidth() != img1.getWidth()) {
    throw new IOException("Images do not have the same width");
  }
  BufferedImage img=new BufferedImage(img0.getWidth(),img0.getHeight() + img1.getHeight(),img0.getType());
  Graphics2D g=img.createGraphics();
  g.drawImage(img0,0,0,null);
  g.drawImage(img1,0,img0.getHeight(),null);
  g.dispose();
  return loadTexture(id,img);
}
 

Example 26

From project Custom-Salem, under directory /src/haven/.

Source file: LocalMiniMap.java

  15 
vote

private void store(BufferedImage img,Coord cg){
  if (!Config.store_map) {
    return;
  }
  Coord c=cg.sub(sp);
  String fileName=String.format("%s/map/%s/tile_%d_%d.png",Config.userhome,session,c.x,c.y);
  File outputfile=new File(fileName);
  try {
    ImageIO.write(img,"png",outputfile);
  }
 catch (  IOException e) {
  }
}
 

Example 27

From project dawn-common, under directory /org.dawb.hdf5/src/ncsa/hdf/view/.

Source file: Tools.java

  15 
vote

/** 
 * Save a BufferedImage into an image file.
 * @param image the BufferedImage to save.
 * @param file the image file.
 * @param type the image type.
 */
public static void saveImageAs(BufferedImage image,File file,String type) throws Exception {
  if (image == null) {
    throw new NullPointerException("The source image is null.");
  }
  ImageIO.write(image,type,file);
}
 

Example 28

From project dawn-ui, under directory /org.dawb.workbench.plotting/src/org/dawb/workbench/plotting/printing/.

Source file: PlotExportPrintUtil.java

  15 
vote

private static void savePostScript(File imageFile,Image image) throws FileNotFoundException {
  ByteArrayOutputStream os=new ByteArrayOutputStream();
  RenderedImage awtImage=convertToAWT(image.getImageData());
  try {
    ImageIO.write(awtImage,"png",os);
  }
 catch (  IOException e) {
    logger.error("Could not write to OutputStream",e);
  }
  try {
    ByteArrayInputStream inputStream=new ByteArrayInputStream(os.toByteArray());
    InputStream is=new BufferedInputStream(inputStream);
    OutputStream fos=new BufferedOutputStream(new FileOutputStream(imageFile.getAbsolutePath()));
    DocFlavor flavor=DocFlavor.INPUT_STREAM.GIF;
    StreamPrintServiceFactory[] factories=StreamPrintServiceFactory.lookupStreamPrintServiceFactories(flavor,DocFlavor.BYTE_ARRAY.POSTSCRIPT.getMimeType());
    if (factories.length > 0) {
      StreamPrintService service=factories[0].getPrintService(fos);
      DocPrintJob job=service.createPrintJob();
      Doc doc=new SimpleDoc(is,flavor,null);
      PrintJobWatcher pjDone=new PrintJobWatcher(job);
      job.print(doc,null);
      pjDone.waitUntilDone();
    }
    is.close();
    fos.close();
  }
 catch (  PrintException e) {
    logger.error("Could not print to PostScript",e);
  }
catch (  IOException e) {
    logger.error("IO error",e);
  }
}
 

Example 29

From project drools-planner, under directory /drools-planner-benchmark/src/main/java/org/drools/planner/benchmark/core/statistic/.

Source file: AbstractProblemStatistic.java

  15 
vote

protected File writeChartToImageFile(JFreeChart chart,String fileNameBase){
  BufferedImage chartImage=chart.createBufferedImage(1024,768);
  File chartFile=new File(problemBenchmark.getProblemReportDirectory(),fileNameBase + ".png");
  OutputStream out=null;
  try {
    out=new FileOutputStream(chartFile);
    ImageIO.write(chartImage,"png",out);
  }
 catch (  IOException e) {
    throw new IllegalArgumentException("Problem writing chartFile: " + chartFile,e);
  }
 finally {
    IOUtils.closeQuietly(out);
  }
  return chartFile;
}
 

Example 30

From project drugis-common, under directory /common-extra/src/main/java/org/drugis/common/gui/.

Source file: ImageExporter.java

  15 
vote

private static void writePNG(String filename,BufferedImage b){
  try {
    ImageIO.write(b,"png",new File(filename));
  }
 catch (  IOException e) {
    throw new RuntimeException(e);
  }
}
 

Example 31

From project edg-examples, under directory /chunchun/src/jbossas/java/com/jboss/datagrid/chunchun/jsf/.

Source file: InitializeCache.java

  15 
vote

private BufferedImage loadImageFromFile(String fileName){
  BufferedImage image=null;
  try {
    image=ImageIO.read(this.getClass().getClassLoader().getResourceAsStream(fileName));
    return image;
  }
 catch (  IOException e) {
    throw new RuntimeException("Unable to load image from file " + fileName);
  }
}
 

Example 32

From project en4j, under directory /NBPlatformApp/NoteContentViewModule/src/main/java/com/rubenlaguna/en4j/NoteContentViewModule/.

Source file: ENMLReplacedElementFactory.java

  15 
vote

private ReplacedElement loadImage(LayoutContext context,String hash){
  ReplacedElement toReturn=null;
  InputStream is=getImage(hash);
  Image image=null;
  if (is == null) {
    return brokenImage(context,100,100);
  }
  try {
    image=ImageIO.read(is);
  }
 catch (  IOException e) {
    LOG.log(Level.WARNING,"exception caught:",e);
  }
 finally {
    try {
      is.close();
    }
 catch (    IOException e) {
    }
  }
  if (image == null) {
    return brokenImage(context,100,100);
  }
  ImageIcon icon=new ImageIcon(image);
  JLabel cc=new JLabel(icon);
  cc.setSize(cc.getPreferredSize());
  FSCanvas canvas=context.getCanvas();
  if (canvas instanceof JComponent) {
    ((JComponent)canvas).add(cc);
  }
  toReturn=new SwingReplacedElement(cc){
    public boolean isRequiresInteractivePaint(){
      return false;
    }
  }
;
  return toReturn;
}
 

Example 33

From project encog-java-core, under directory /src/main/java/org/encog/ca/program/generic/.

Source file: GenericIO.java

  15 
vote

public static void save(CARunner runner,File f){
  try {
    EncogDirectoryPersistence.saveObject(new File(FileUtil.forceExtension(f.toString(),"eg")),runner.getUniverse());
    SerializeObject.save(new File(FileUtil.forceExtension(f.toString(),"bin")),(Serializable)runner.getPhysics());
    BasicCAVisualizer visualizer=new BasicCAVisualizer(runner.getUniverse());
    Image img=visualizer.visualize();
    ImageIO.write((RenderedImage)img,"png",new File(FileUtil.forceExtension(f.toString(),"png")));
  }
 catch (  IOException ex) {
    throw new CellularAutomataError(ex);
  }
}
 

Example 34

From project encog-java-examples, under directory /src/main/java/org/encog/examples/neural/image/.

Source file: ImageNeuralNetwork.java

  15 
vote

private void processNetwork() throws IOException {
  System.out.println("Downsampling images...");
  for (  final ImagePair pair : this.imageList) {
    final MLData ideal=new BasicMLData(this.outputCount);
    final int idx=pair.getIdentity();
    for (int i=0; i < this.outputCount; i++) {
      if (i == idx) {
        ideal.setData(i,1);
      }
 else {
        ideal.setData(i,-1);
      }
    }
    final Image img=ImageIO.read(pair.getFile());
    final ImageMLData data=new ImageMLData(img);
    this.training.add(data,ideal);
  }
  final String strHidden1=getArg("hidden1");
  final String strHidden2=getArg("hidden2");
  this.training.downsample(this.downsampleHeight,this.downsampleWidth);
  final int hidden1=Integer.parseInt(strHidden1);
  final int hidden2=Integer.parseInt(strHidden2);
  this.network=EncogUtility.simpleFeedForward(this.training.getInputSize(),hidden1,hidden2,this.training.getIdealSize(),true);
  System.out.println("Created network: " + this.network.toString());
}
 

Example 35

From project encog-java-workbench, under directory /src/main/java/org/encog/workbench/tabs/files/.

Source file: ImageFileTab.java

  15 
vote

public ImageFileTab(ProjectFile file){
  super(file);
  try {
    this.image=ImageIO.read(file.getFile());
  }
 catch (  IOException e) {
    EncogWorkBench.displayError("Error Loading Image",e);
  }
}
 

Example 36

From project engine, under directory /main/com/midtro/platform/modules/assets/types/.

Source file: ImageAssembler.java

  15 
vote

/** 
 * {@inheritDoc}
 */
@Override public void assemble(String assetName,String fileName,AssetConfig config,Map<String,Asset<?>> store) throws Exception {
  Image img=null;
switch (config.getMountType()) {
case FILE:
    img=ImageIO.read(new File(config.getFileLocation() + fileName.replace('/',File.separatorChar)));
  break;
case CACHE:
img=ImageIO.read(new File(config.getCacheLocation() + fileName.replace('/',File.separatorChar)));
break;
case URL:
img=ImageIO.read(new URL(config.getUrlLocation() + fileName));
break;
default :
throw new IllegalStateException("Unknown mount type");
}
store.put("image." + assetName,new ImageAsset(assetName,img));
}
 

Example 37

From project entando-core-engine, under directory /src/main/java/com/agiletec/plugins/jacms/aps/system/services/resource/model/imageresizer/.

Source file: DefaultImageResizer.java

  15 
vote

@Override public void saveResizedImage(ImageIcon imageIcon,String filePath,ImageResourceDimension dimension) throws ApsSystemException {
  Image image=imageIcon.getImage();
  double scale=this.computeScale(image.getWidth(null),image.getHeight(null),dimension.getDimx(),dimension.getDimy());
  int scaledW=(int)(scale * image.getWidth(null));
  int scaledH=(int)(scale * image.getHeight(null));
  BufferedImage outImage=new BufferedImage(scaledW,scaledH,BufferedImage.TYPE_INT_RGB);
  AffineTransform tx=new AffineTransform();
  tx.scale(scale,scale);
  Graphics2D g2d=outImage.createGraphics();
  g2d.setRenderingHint(RenderingHints.KEY_RENDERING,RenderingHints.VALUE_RENDER_QUALITY);
  g2d.setRenderingHint(RenderingHints.KEY_COLOR_RENDERING,RenderingHints.VALUE_COLOR_RENDER_QUALITY);
  g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING,RenderingHints.VALUE_ANTIALIAS_ON);
  g2d.drawImage(image,tx,null);
  g2d.dispose();
  try {
    File file=new File(filePath);
    ImageIO.write(outImage,this.getFileExtension(filePath),file);
  }
 catch (  Throwable t) {
    String msg=this.getClass().getName() + ": saveImageResized: " + t.toString();
    ApsSystemUtils.getLogger().throwing(this.getClass().getName(),"saveImageResized",t);
    throw new ApsSystemException(msg,t);
  }
}
 

Example 38

From project faces, under directory /Proyectos/showcase/src/main/java/org/primefaces/examples/view/.

Source file: DynamicImageController.java

  15 
vote

public DynamicImageController(){
  try {
    BufferedImage bufferedImg=new BufferedImage(100,25,BufferedImage.TYPE_INT_RGB);
    Graphics2D g2=bufferedImg.createGraphics();
    g2.drawString("This is a text",0,10);
    ByteArrayOutputStream os=new ByteArrayOutputStream();
    ImageIO.write(bufferedImg,"png",os);
    graphicText=new DefaultStreamedContent(new ByteArrayInputStream(os.toByteArray()),"image/png");
    JFreeChart jfreechart=ChartFactory.createPieChart("Turkish Cities",createDataset(),true,true,false);
    File chartFile=new File("dynamichart");
    ChartUtilities.saveChartAsPNG(chartFile,jfreechart,375,300);
    chart=new DefaultStreamedContent(new FileInputStream(chartFile),"image/png");
    File barcodeFile=new File("dynamicbarcode");
    BarcodeImageHandler.saveJPEG(BarcodeFactory.createCode128("PRIMEFACES"),barcodeFile);
    barcode=new DefaultStreamedContent(new FileInputStream(barcodeFile),"image/jpeg");
  }
 catch (  Exception e) {
    e.printStackTrace();
  }
}
 

Example 39

From project FBReaderJ, under directory /obsolete/swing/src/org/geometerplus/zlibrary/ui/swing/image/.

Source file: ZLSwingImageManager.java

  15 
vote

public ZLSwingImageData getImageData(ZLImage image){
  if (image instanceof ZLSingleImage) {
    if ("image/palm".equals(((ZLSingleImage)image).mimeType())) {
      return new ZLSwingImageData(convertFromPalmImageFormat(((ZLSingleImage)image).byteData()));
    }
    try {
      final BufferedImage awtImage=ImageIO.read(new ByteArrayInputStream(((ZLSingleImage)image).byteData()));
      return new ZLSwingImageData(awtImage);
    }
 catch (    IOException e) {
      return null;
    }
  }
 else {
    return null;
  }
}
 

Example 40

From project flyingsaucer, under directory /flying-saucer-core/src/main/java/org/xhtmlrenderer/swing/.

Source file: ImageResourceLoader.java

  15 
vote

public static ImageResource loadImageResourceFromUri(final String uri){
  StreamResource sr=new StreamResource(uri);
  InputStream is;
  ImageResource ir=null;
  try {
    sr.connect();
    is=sr.bufferedStream();
    try {
      BufferedImage img=ImageIO.read(is);
      if (img == null) {
        throw new IOException("ImageIO.read() returned null");
      }
      ir=createImageResource(uri,img);
    }
 catch (    FileNotFoundException e) {
      XRLog.exception("Can't read image file; image at URI '" + uri + "' not found");
    }
catch (    IOException e) {
      XRLog.exception("Can't read image file; unexpected problem for URI '" + uri + "'",e);
    }
 finally {
      sr.close();
    }
  }
 catch (  IOException e) {
    XRLog.exception("Can't open stream for URI '" + uri + "': "+ e.getMessage());
  }
  if (ir == null) {
    ir=createImageResource(uri,null);
  }
  return ir;
}
 

Example 41

From project FML, under directory /client/cpw/mods/fml/client/.

Source file: TextureFXManager.java

  15 
vote

public BufferedImage loadImageFromTexturePack(RenderEngine renderEngine,String path) throws IOException {
  InputStream image=client.field_71418_C.func_77292_e().func_77532_a(path);
  if (image == null) {
    throw new RuntimeException(String.format("The requested image path %s is not found",path));
  }
  BufferedImage result=ImageIO.read(image);
  if (result == null) {
    throw new RuntimeException(String.format("The requested image path %s appears to be corrupted",path));
  }
  return result;
}
 

Example 42

From project frame, under directory /src/main/java/twigkit/frame/.

Source file: CachedImageIOService.java

  15 
vote

@Override public Image fromURL(final URL url) throws IOException {
  if (repository != null && repository.exists()) {
    if (logger.isDebugEnabled()) {
      logger.debug("Getting Image from cache [" + repository.getAbsolutePath() + "]");
    }
    File file=getFileFromURL(url,0,0);
    if (file.exists()) {
      if (logger.isDebugEnabled()) {
        logger.debug("Getting Image [" + file.getName() + "] from cache");
      }
      BufferedImage buf=ImageIO.read(file);
      Image image=new Image(buf);
      image.setUrl(url);
      return image;
    }
 else {
      Image image=super.fromURL(url);
      image.setUrl(url);
      ImageIO.write(image.getBufferedImage(),Image.ContentType.PNG.getSuffix(),file);
      if (logger.isDebugEnabled()) {
        logger.debug("Wrote Image (original) [" + file.getName() + ", "+ image.getWidth()+ "px by "+ image.getHeight()+ "px] to cache");
      }
      return image;
    }
  }
  logger.warn("Failed to cache Image [" + url + "], returning without caching!");
  return super.fromURL(url);
}
 

Example 43

From project freemind, under directory /freemind/accessories/plugins/.

Source file: ExportToImage.java

  15 
vote

/** 
 * Export image.
 */
public boolean exportToImage(BufferedImage image,String type,String description){
  File chosenFile=chooseFile(type,description,null);
  if (chosenFile == null) {
    return false;
  }
  try {
    getController().getFrame().setWaitingCursor(true);
    FileOutputStream out=new FileOutputStream(chosenFile);
    ImageIO.write(image,type,out);
    out.close();
  }
 catch (  IOException e1) {
    freemind.main.Resources.getInstance().logException(e1);
  }
  getController().getFrame().setWaitingCursor(false);
  return true;
}
 

Example 44

From project GAIL, under directory /src/gail/grid/.

Source file: Resources.java

  15 
vote

/** 
 * Loads image resources inside the .jar packege. For example, if "image.jpg" is into the foo.bar package, the string to  load it would be "/foo/bar/image.jpg".
 * @param resourceLocation
 * @return 
 */
public static BufferedImage loadImageResource(String resourceLocation){
  URL url=Resources.class.getResource(resourceLocation);
  BufferedImage img=null;
  try {
    img=ImageIO.read(url);
  }
 catch (  IOException ex) {
    Logger.getLogger(Resources.class.getName()).log(Level.SEVERE,null,ex);
  }
  return img;
}
 

Example 45

From project Game_3, under directory /java/src/playn/java/.

Source file: JavaAssets.java

  15 
vote

@Override protected Image doGetImage(String path){
  JavaGraphics graphics=platform.graphics();
  Exception error=null;
  for (  Scale.ScaledResource rsrc : graphics.ctx().scale.getScaledResources(pathPrefix + path)) {
    try {
      return graphics.createStaticImage(ImageIO.read(requireResource(rsrc.path)),rsrc.scale);
    }
 catch (    FileNotFoundException fnfe) {
      error=fnfe;
    }
catch (    Exception e) {
      error=e;
      break;
    }
  }
  PlayN.log().warn("Could not load image: " + pathPrefix + path,error);
  return graphics.createErrorImage(error != null ? error : new FileNotFoundException(path));
}
 

Example 46

From project GeoBI, under directory /print/src/main/java/org/mapfish/print/output/.

Source file: ImageOutputFactory.java

  15 
vote

private void drawImage(OutputStream out,List<? extends RenderedImage> images) throws IOException {
  ParameterBlock pbMosaic=new ParameterBlock();
  float height=0;
  float width=0;
  int i=0;
  for (  RenderedImage source : images) {
    i++;
    LOGGER.debug("Adding page image " + i + " bounds: ["+ 0+ ","+ height+ " "+ source.getWidth()+ ","+ (height + source.getHeight())+ "]");
    ParameterBlock pbTranslate=new ParameterBlock();
    pbTranslate.addSource(source);
    pbTranslate.add(0f);
    pbTranslate.add(height);
    RenderedOp translated=JAI.create("translate",pbTranslate);
    pbMosaic.addSource(translated);
    height+=source.getHeight() + MARGIN;
    if (width < source.getWidth())     width=source.getWidth();
  }
  TileCache cache=JAI.createTileCache((long)(height * width * 400));
  RenderingHints hints=new RenderingHints(JAI.KEY_TILE_CACHE,cache);
  RenderedOp mosaic=JAI.create("mosaic",pbMosaic,hints);
  ImageIO.write(mosaic,"TIFF",out);
}
 

Example 47

From project geolatte-maprenderer, under directory /src/main/java/org/geolatte/maprenderer/sld/graphics/.

Source file: ExternalGraphicsRepository.java

  15 
vote

/** 
 * Retrieves image or SVG from path and stores it in the cache (svg or image cache)
 * @param uri
 * @param path
 * @throws IOException
 */
private void retrieveAndStore(String uri,String path) throws IOException {
  InputStream inputStream=getResourceAsInputStream(path);
  if (inputStream == null) {
    throw new IOException(String.format("Graphics file %s not found on classpath.",path));
  }
  BufferedImage img=ImageIO.read(inputStream);
  if (img != null) {
    storeInCache(new ImageKey(uri),img);
    return;
  }
  inputStream=getResourceAsInputStream(path);
  SVGDocument svg=SVGDocumentIO.read(uri,inputStream);
  if (svg != null) {
    storeInSvgCache(uri,svg);
    return;
  }
  throw new IOException("File " + path + " is neither image nor svg.");
}
 

Example 48

From project geolatte-mapserver, under directory /src/main/java/org/geolatte/mapserver/img/.

Source file: JAIImaging.java

  15 
vote

/** 
 * {@inheritDoc}
 */
@Override public TileImage read(InputStream is,int x,int y,boolean forceArgb) throws IOException {
  BufferedImage bi=ImageIO.read(is);
  if (forceArgb) {
    BufferedImage rgbImage=new BufferedImage(bi.getWidth(),bi.getHeight(),BufferedImage.TYPE_INT_ARGB);
    rgbImage.createGraphics().drawImage(bi,0,0,null,null);
    bi=rgbImage;
  }
  RenderedOp op=TranslateDescriptor.create(bi,(float)x,(float)y,null,null);
  PlanarImage image=op.createInstance();
  return new JAITileImage(image);
}
 

Example 49

From project geronimo-javamail, under directory /geronimo-javamail_1.4/geronimo-javamail_1.4_provider/src/main/java/org/apache/geronimo/javamail/handlers/.

Source file: AbstractImageHandler.java

  15 
vote

public Object getContent(DataSource ds) throws IOException {
  Iterator i=ImageIO.getImageReadersByMIMEType(flavour.getMimeType());
  if (!i.hasNext()) {
    throw new UnsupportedDataTypeException("Unknown image type " + flavour.getMimeType());
  }
  ImageReader reader=(ImageReader)i.next();
  ImageInputStream iis=ImageIO.createImageInputStream(ds.getInputStream());
  reader.setInput(iis);
  return reader.read(0);
}
 

Example 50

From project gitblit, under directory /src/com/gitblit/build/.

Source file: BuildThumbnails.java

  15 
vote

/** 
 * Return the dimensions of the specified image file.
 * @param file
 * @return dimensions of the image
 * @throws IOException
 */
public static Dimension getImageDimensions(File file) throws IOException {
  ImageInputStream in=ImageIO.createImageInputStream(file);
  try {
    final Iterator<ImageReader> readers=ImageIO.getImageReaders(in);
    if (readers.hasNext()) {
      ImageReader reader=readers.next();
      try {
        reader.setInput(in);
        return new Dimension(reader.getWidth(0),reader.getHeight(0));
      }
  finally {
        reader.dispose();
      }
    }
  }
  finally {
    if (in != null) {
      in.close();
    }
  }
  return null;
}
 

Example 51

From project glg2d, under directory /src/test/java/glg2d/.

Source file: StressTest.java

  15 
vote

@Test public void imageTest() throws Exception {
  final int numimages=1000;
  final Image image=ImageIO.read(StressTest.class.getClassLoader().getResource("duke.gif"));
  TimedPainter painter=new TimedPainter(){
    @Override protected void paint(    Graphics2D g2d){
      int x=300;
      int y=400;
      for (int i=0; i < numimages; i++) {
        g2d.drawImage(image,rand.nextInt(x),rand.nextInt(y),rand.nextInt(x),rand.nextInt(y),null);
      }
    }
  }
;
  tester.setPainter(painter);
  painter.waitAndLogTimes("images");
}
 

Example 52

From project Gmote, under directory /gmoteserver/src/org/gmote/server/.

Source file: GmoteHttpServer.java

  15 
vote

private void sendImage(File originalImagePath,BufferedOutputStream dataOut) throws InterruptedException, ImageFormatException, IOException {
  LOGGER.info("Converting image to smaller scale");
  Image image=Toolkit.getDefaultToolkit().getImage(originalImagePath.getAbsolutePath());
  MediaTracker mediaTracker=new MediaTracker(new Container());
  mediaTracker.addImage(image,0);
  mediaTracker.waitForID(0);
  int imageWidth=image.getWidth(null);
  int imageHeight=image.getHeight(null);
  int thumbWidth=imageWidth;
  int thumbHeight=imageHeight;
  int MAX_SIZE=500;
  if (imageWidth > MAX_SIZE || imageHeight > MAX_SIZE) {
    double imageRatio=(double)imageWidth / (double)imageHeight;
    if (imageWidth > imageHeight) {
      thumbWidth=MAX_SIZE;
      thumbHeight=(int)(thumbWidth / imageRatio);
    }
 else {
      thumbHeight=MAX_SIZE;
      thumbWidth=(int)(thumbHeight * imageRatio);
    }
  }
  BufferedImage thumbImage;
  thumbImage=new BufferedImage(thumbWidth,thumbHeight,BufferedImage.TYPE_INT_RGB);
  Graphics2D graphics2D=thumbImage.createGraphics();
  graphics2D.setRenderingHint(RenderingHints.KEY_INTERPOLATION,RenderingHints.VALUE_INTERPOLATION_BILINEAR);
  graphics2D.drawImage(image,0,0,thumbWidth,thumbHeight,null);
  if (PlatformUtil.isLinux()) {
    ImageIO.write(thumbImage,"JPEG",dataOut);
  }
 else {
    JPEGImageEncoder encoder=JPEGCodec.createJPEGEncoder(dataOut);
    JPEGEncodeParam param=encoder.getDefaultJPEGEncodeParam(thumbImage);
    float quality=80;
    param.setQuality(quality / 100.0f,false);
    encoder.encode(thumbImage,param);
  }
  dataOut.close();
  LOGGER.info("Done sending image");
}
 

Example 53

From project GraphLab, under directory /src/graphlab/graph/graph/.

Source file: GraphModel.java

  15 
vote

public void setBackgroundImageFile(File imageFile){
  backgroundImageFile=imageFile;
  try {
    backgroundImage=ImageIO.read(imageFile);
  }
 catch (  Exception e) {
    System.out.println("Error loading image file");
  }
  fireGraphChange(REPAINT_GRAPH_GRAPH_CHANGE,null,null);
}
 

Example 54

From project greenhouse, under directory /src/main/java/com/springsource/greenhouse/utils/.

Source file: ImageUtils.java

  15 
vote

/** 
 * Scale the image stored in the byte array to a specific width.
 */
public static byte[] scaleImageToWidth(byte[] originalBytes,int scaledWidth) throws IOException {
  BufferedImage originalImage=ImageIO.read(new ByteArrayInputStream(originalBytes));
  int originalWidth=originalImage.getWidth();
  if (originalWidth <= scaledWidth) {
    return originalBytes;
  }
  int scaledHeight=(int)(originalImage.getHeight() * ((float)scaledWidth / (float)originalWidth));
  BufferedImage scaledImage=new BufferedImage(scaledWidth,scaledHeight,BufferedImage.TYPE_INT_RGB);
  Graphics2D g=scaledImage.createGraphics();
  g.drawImage(originalImage,0,0,scaledWidth,scaledHeight,null);
  g.dispose();
  ByteArrayOutputStream byteStream=new ByteArrayOutputStream();
  ImageIO.write(scaledImage,"jpeg",byteStream);
  return byteStream.toByteArray();
}
 

Example 55

From project gridland, under directory /src/org/grid/server/.

Source file: Field.java

  15 
vote

private static Dimension loadImage(File f,Set<Position>[] flags,Position[] hqs,Vector<Position> walls) throws IOException {
  BufferedImage src=ImageIO.read(f);
  for (int j=0; j < src.getHeight(); j++) {
    for (int i=0; i < src.getWidth(); i++) {
      Color color=new Color(src.getRGB(i,j));
      if (color.getRed() == color.getBlue() && color.getRed() == color.getGreen()) {
        if (color.getRed() < 200) {
          walls.add(new Position(i,j));
        }
        continue;
      }
      float[] hsv=Color.RGBtoHSB(color.getRed(),color.getGreen(),color.getBlue(),null);
      int team=Math.min(flags.length - 1,Math.round(hsv[0] * flags.length));
      if (hsv[2] > 0.5) {
        flags[team].add(new Position(i,j));
      }
 else {
        hqs[team]=new Position(i,j);
      }
    }
  }
  return new Dimension(src.getWidth(),src.getHeight());
}
 

Example 56

From project gs-core, under directory /src/org/graphstream/stream/file/.

Source file: FileSinkImages.java

  15 
vote

public AddLogoRenderer(String logoFile,int x,int y) throws IOException {
  File f=new File(logoFile);
  if (f.exists())   this.logo=ImageIO.read(f);
 else   this.logo=ImageIO.read(ClassLoader.getSystemResource(logoFile));
  this.x=x;
  this.y=y;
}
 

Example 57

From project gs-tool, under directory /src/org/graphstream/tool/gui/.

Source file: Resources.java

  15 
vote

public static Image getImage(String url,int width,int height,boolean keepAspect){
  InputStream in=ToolGUI.class.getClassLoader().getResourceAsStream(url);
  BufferedImage image;
  try {
    image=ImageIO.read(in);
  }
 catch (  IOException e) {
    image=new BufferedImage(width,height,BufferedImage.TYPE_INT_ARGB);
  }
  boolean validWidth=(width <= 0 || width == image.getWidth());
  boolean validHeight=(height <= 0 || height == image.getHeight());
  if ((validWidth && !validHeight && !keepAspect) || (validHeight && !validWidth && !keepAspect) || (!validWidth && !validHeight)) {
    if (keepAspect) {
      double ratio=image.getWidth() / (double)image.getHeight();
      width=validWidth ? width : (int)(ratio * height);
      height=validWidth ? (int)(width / ratio) : height;
    }
    return image.getScaledInstance(width,height,BufferedImage.SCALE_SMOOTH);
  }
  return image;
}
 

Example 58

From project guj.com.br, under directory /src/net/jforum/util/.

Source file: Captcha.java

  15 
vote

public void writeCaptchaImage(){
  BufferedImage image=SessionFacade.getUserSession().getCaptchaImage();
  if (image == null) {
    return;
  }
  OutputStream outputStream=null;
  try {
    outputStream=JForumExecutionContext.getResponse().getOutputStream();
    ImageIO.write(image,"jpg",outputStream);
  }
 catch (  IOException ex) {
    logger.error(ex);
  }
 finally {
    if (outputStream != null) {
      try {
        outputStream.close();
      }
 catch (      IOException ex) {
      }
    }
  }
}
 

Example 59

From project Haven-and-Hearth-client-modified-by-Ender, under directory /src/haven/.

Source file: MiniMap.java

  15 
vote

public void saveCaveMaps(){
synchronized (caveTex) {
    Coord rc=null;
    String sess=Utils.sessdate(System.currentTimeMillis());
    File outputfile=new File("cave/" + sess);
    try {
      Writer currentSessionFile=new FileWriter("cave/currentsession.js");
      currentSessionFile.write("var currentSession = '" + sess + "';\n");
      currentSessionFile.close();
    }
 catch (    IOException e1) {
    }
    outputfile.mkdirs();
    for (    Coord c : caveTex.keySet()) {
      if (rc == null) {
        rc=c;
      }
      TexI tex=(TexI)caveTex.get(c);
      c=c.sub(rc);
      String fileName="tile_" + c.x + "_"+ c.y;
      outputfile=new File("cave/" + sess + "/"+ fileName+ ".png");
      try {
        ImageIO.write(tex.back,"png",outputfile);
      }
 catch (      IOException e) {
      }
    }
  }
}
 

Example 60

From project Hesperid, under directory /server/src/main/java/ch/astina/hesperid/web/pages/report/.

Source file: ReportIndex.java

  15 
vote

protected JasperPrint createReport() throws Exception {
  JasperDesign jasperDesign=JRXmlLoader.load(new ByteArrayInputStream(reportType.getJasperXmlCode().getBytes()));
  JasperReport jasperReport=JasperCompileManager.compileReport(jasperDesign);
  Map<String,Object> parameters=new HashMap<String,Object>();
  Image logo=ImageIO.read(getClass().getClassLoader().getResourceAsStream("hesperid-logo-blue-big.jpeg"));
  parameters.put("logo",logo);
  parameters.put("reportTitle",reportType.getName());
  List hqlResult=hqlDAO.getExecuteHql(reportType.getHqlQuery());
  JRBeanCollectionDataSource hqlResultDataSource=new JRBeanCollectionDataSource(hqlResult);
  JasperPrint jasperPrint=JasperFillManager.fillReport(jasperReport,parameters,hqlResultDataSource);
  return jasperPrint;
}
 

Example 61

From project HiTune_1, under directory /chukwa-hitune-dist/src/java/org/apache/hadoop/chukwa/hicc/.

Source file: ImageSlicer.java

  15 
vote

public BufferedImage prepare(String filename){
  try {
    src=ImageIO.read(new File(filename));
  }
 catch (  IOException e) {
    log.error("Image file does not exist:" + filename + ", can not render image.");
  }
  XYData fullSize=new XYData(1,1);
  while (fullSize.getX() < src.getWidth() || fullSize.getY() < src.getHeight()) {
    fullSize.set(fullSize.getX() * 2,fullSize.getY() * 2);
  }
  float scaleX=(float)fullSize.getX() / src.getWidth();
  float scaleY=(float)fullSize.getY() / src.getHeight();
  log.info("Image size: (" + src.getWidth() + ","+ src.getHeight()+ ")");
  log.info("Scale size: (" + scaleX + ","+ scaleY+ ")");
  AffineTransform at=AffineTransform.getScaleInstance(scaleX,scaleY);
  AffineTransformOp op=new AffineTransformOp(at,AffineTransformOp.TYPE_BILINEAR);
  BufferedImage dest=op.filter(src,null);
  return dest;
}
 

Example 62

From project Holo-Edit, under directory /holoedit/opengl/.

Source file: OpenGLUt.java

  15 
vote

private static BufferedImage readPNGImage(String resourceName){
  try {
    File f=new File("./images/" + resourceName);
    if (f.exists()) {
      BufferedImage img=ImageIO.read(f);
      java.awt.geom.AffineTransform tx=java.awt.geom.AffineTransform.getScaleInstance(1,-1);
      tx.translate(0,-img.getHeight(null));
      AffineTransformOp op=new AffineTransformOp(tx,AffineTransformOp.TYPE_NEAREST_NEIGHBOR);
      img=op.filter(img,null);
      return img;
    }
  }
 catch (  IOException e) {
    e.printStackTrace();
  }
  return null;
}
 

Example 63

From project Hphoto, under directory /src/java/com/hphoto/server/.

Source file: VerifyCodeImage.java

  15 
vote

public String saveVerifyImage(int width,int height,OutputStream out) throws IOException {
  GraphicsEnvironment ge=GraphicsEnvironment.getLocalGraphicsEnvironment();
  BufferedImage image=new BufferedImage(width,height,BufferedImage.TYPE_BYTE_INDEXED);
  Graphics2D g=(Graphics2D)image.getGraphics();
  g.setColor(new Color(0xFFFFFF));
  g.fillRect(0,0,width,height);
  String word;
  if (this.word == null)   word=getWord(4);
 else   word=this.word;
  float w=(float)(width * 0.9F);
  float h=(float)(height * 0.2F);
  int d=(int)(w / word.length());
  RenderingHints hints=new RenderingHints(RenderingHints.KEY_ANTIALIASING,RenderingHints.VALUE_ANTIALIAS_ON);
  hints.add(new RenderingHints(RenderingHints.KEY_RENDERING,RenderingHints.VALUE_RENDER_QUALITY));
  g.setRenderingHints(hints);
  Font font=getFont();
  char[] wc=word.toCharArray();
  FontRenderContext frc=g.getFontRenderContext();
  g.setColor(getColor());
  g.setFont(font);
  GlyphVector gv=font.createGlyphVector(frc,wc);
  double charWitdth=gv.getVisualBounds().getWidth();
  int startPosX=(int)(width - charWitdth) / 2;
  g.drawChars(wc,0,wc.length,startPosX,height / 2 + (int)(height * 0.1));
  Captcha ca=captcha[generator.nextInt(captcha.length)];
  ca.setRange(w);
  image=ca.getDistortedImage(image);
  ImageIO.write(image,"JPEG",out);
  return word;
}
 

Example 64

From project huiswerk, under directory /print/zxing-1.6/core/test/src/com/google/zxing/common/.

Source file: AbstractNegativeBlackBoxTestCase.java

  15 
vote

@Override public void testBlackBox() throws IOException {
  assertFalse(testResults.isEmpty());
  File[] imageFiles=getImageFiles();
  int[] falsePositives=new int[testResults.size()];
  for (  File testImage : imageFiles) {
    System.out.println("Starting " + testImage.getAbsolutePath());
    BufferedImage image=ImageIO.read(testImage);
    if (image == null) {
      throw new IOException("Could not read image: " + testImage);
    }
    for (int x=0; x < testResults.size(); x++) {
      if (!checkForFalsePositives(image,testResults.get(x).getRotation())) {
        falsePositives[x]++;
      }
    }
  }
  for (int x=0; x < testResults.size(); x++) {
    System.out.println("Rotation " + testResults.get(x).getRotation() + " degrees: "+ falsePositives[x]+ " of "+ imageFiles.length+ " images were false positives ("+ testResults.get(x).getFalsePositivesAllowed()+ " allowed)");
    assertTrue("Rotation " + testResults.get(x).getRotation() + " degrees: "+ "Too many false positives found",falsePositives[x] <= testResults.get(x).getFalsePositivesAllowed());
  }
}
 

Example 65

From project imageflow, under directory /src/de/danielsenff/imageflow/.

Source file: ImageFlowView.java

  15 
vote

private void initAppIcon(){
  try {
    this.getFrame().setIconImage(ImageIO.read(this.getClass().getResourceAsStream(getResourceString("mainFrame.icon"))));
  }
 catch (  IOException e) {
    e.printStackTrace();
  }
}
 

Example 66

From project imgscalr, under directory /src/test/java/org/imgscalr/.

Source file: AbstractScalrTest.java

  15 
vote

protected static BufferedImage load(String name){
  BufferedImage i=null;
  try {
    i=ImageIO.read(AbstractScalrTest.class.getResource(name));
  }
 catch (  Exception e) {
    e.printStackTrace();
  }
  return i;
}
 

Example 67

From project ISAcreator, under directory /src/main/java/org/isatools/isacreator/filechooser/.

Source file: FileImage.java

  15 
vote

/** 
 * Save the image to a pre-defined location todo fall back on a generic default image if writing fails
 */
private void saveImage() throws IOException {
  int w=WIDTH;
  int h=HEIGHT;
  BufferedImage img=new BufferedImage(w,h,BufferedImage.TYPE_INT_RGB);
  Graphics2D g2=img.createGraphics();
  g2.setColor(UIHelper.BG_COLOR);
  g2.fillRect(0,0,WIDTH,HEIGHT);
  paint(g2);
  g2.dispose();
  String ext="png";
  File f=new File(FILE_IMG_DIR);
  if (!f.exists()) {
    f.mkdirs();
  }
  ImageIO.write(img,ext,new File(FILE_IMG_DIR + "/" + extension+ "icon."+ ext));
}
 

Example 68

From project JaamSim, under directory /com/eteks/sweethome3d/j3d/.

Source file: DAELoader.java

  15 
vote

/** 
 * Handles the end tag of elements children of "image".
 */
private void handleImageElementsEnd(String name) throws SAXException {
  if ("init_from".equals(name)) {
    try {
      URL textureImageUrl=new URL(baseUrl,getCharacters());
      BufferedImage textureImage=ImageIO.read(textureImageUrl);
      if (textureImage != null) {
        TextureLoader textureLoader=new TextureLoader(textureImage);
        Texture texture=textureLoader.getTexture();
        texture.setUserData(textureImageUrl);
        this.textures.put(this.imageId,texture);
      }
    }
 catch (    IOException ex) {
      InputAgent.logWarning("%s: \"%s: %s\"",this.baseUrl,ex,getCharacters());
    }
  }
 else   if ("data".equals(name)) {
    throw new SAXException("<data> not supported");
  }
}
 

Example 69

From project jagger, under directory /chassis/core/src/main/java/com/griddynamics/jagger/engine/e1/reporting/.

Source file: StatusImageProvider.java

  15 
vote

public void setStatusImageOKLocation(Resource statusImageOKLocation){
  try {
    this.statusImageOK=ImageIO.read(statusImageOKLocation.getInputStream());
  }
 catch (  IOException e) {
    log.error("Failed to resolve image [" + statusImageOKLocation + "]");
  }
}
 

Example 70

From project jAPS2, under directory /src/com/agiletec/plugins/jacms/aps/system/services/resource/model/imageresizer/.

Source file: DefaultImageResizer.java

  15 
vote

@Override public void saveResizedImage(ImageIcon imageIcon,String filePath,ImageResourceDimension dimension) throws ApsSystemException {
  Image image=imageIcon.getImage();
  double scale=this.computeScale(image.getWidth(null),image.getHeight(null),dimension.getDimx(),dimension.getDimy());
  int scaledW=(int)(scale * image.getWidth(null));
  int scaledH=(int)(scale * image.getHeight(null));
  BufferedImage outImage=new BufferedImage(scaledW,scaledH,BufferedImage.TYPE_INT_RGB);
  AffineTransform tx=new AffineTransform();
  tx.scale(scale,scale);
  Graphics2D g2d=outImage.createGraphics();
  g2d.setRenderingHint(RenderingHints.KEY_RENDERING,RenderingHints.VALUE_RENDER_QUALITY);
  g2d.setRenderingHint(RenderingHints.KEY_COLOR_RENDERING,RenderingHints.VALUE_COLOR_RENDER_QUALITY);
  g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING,RenderingHints.VALUE_ANTIALIAS_ON);
  g2d.drawImage(image,tx,null);
  g2d.dispose();
  try {
    File file=new File(filePath);
    ImageIO.write(outImage,this.getFileExtension(filePath),file);
  }
 catch (  Throwable t) {
    String msg=this.getClass().getName() + ": saveImageResized: " + t.toString();
    ApsSystemUtils.getLogger().throwing(this.getClass().getName(),"saveImageResized",t);
    throw new ApsSystemException(msg,t);
  }
}
 

Example 71

From project jASM_16, under directory /src/main/java/de/codesourcery/jasm16/emulator/devices/impl/.

Source file: DefaultScreen.java

  15 
vote

private synchronized BufferedImage getDefaultFontImage(Graphics2D target){
  if (defaultFontImage == null) {
    final ClassPathResource resource=new ClassPathResource("default_font.png",ResourceType.UNKNOWN);
    try {
      final InputStream in=resource.createInputStream();
      try {
        return ImageIO.read(in);
      }
  finally {
        IOUtils.closeQuietly(in);
      }
    }
 catch (    IOException e) {
      LOG.error("getDefaultFontImage(): Internal error, failed to load default font image 'default_font.png'",e);
      throw new RuntimeException(e);
    }
  }
  return defaultFontImage;
}
 

Example 72

From project JavaStory, under directory /Core/src/main/java/javastory/xml/.

Source file: FileStoredPngWzCanvas.java

  15 
vote

private void loadImageIfNecessary(){
  if (this.image == null) {
    try {
      this.image=ImageIO.read(this.file);
      this.width=this.image.getWidth();
      this.height=this.image.getHeight();
    }
 catch (    final IOException e) {
      throw new RuntimeException(e);
    }
  }
}
 

Example 73

From project jbpm-plugin, under directory /jbpm/src/main/java/hudson/jbpm/model/.

Source file: ProcessInstanceAction.java

  15 
vote

public void doImage(StaplerRequest req,StaplerResponse rsp) throws IOException, XPathExpressionException, DocumentException {
  ProcessInstance processInstance=getProcessInstance();
  GPD gpd=getGPD();
  ServletOutputStream output=rsp.getOutputStream();
  ProcessInstanceRenderer panel=new ProcessInstanceRenderer(processInstance,gpd);
  BufferedImage aimg=new BufferedImage(panel.getWidth(),panel.getHeight(),BufferedImage.TYPE_INT_RGB);
  Graphics2D g=aimg.createGraphics();
  panel.paint(g);
  g.dispose();
  ImageIO.write(aimg,"png",output);
  output.flush();
  output.close();
}
 

Example 74

From project jCAE, under directory /viewer3d/src/org/jcae/viewer3d/test/.

Source file: Main.java

  15 
vote

static void testOffscreen() throws ParserConfigurationException, SAXException, IOException {
  View feView2=new View(null,true);
  ViewableFE fev2=new ViewableFE(new AmibeProvider(new File("/var/tmp/mesh")));
  feView2.add(fev2);
  feView2.fitAll();
  feView2.setOriginAxisVisible(true);
  ImageIO.write(feView2.takeSnapshot(4096,4096),"png",File.createTempFile("jcae-viewer3d-snap",".png"));
}
 

Example 75

From project JDE-Samples, under directory /com/rim/samples/server/gpsdemo/.

Source file: SpeedAltitudePlot.java

  15 
vote

public static void createCombinedChart(Collection c){
  RenderedImage rendImage=drawPlot(c);
  File file=new File("Plot.jpg");
  try {
    ImageIO.write(rendImage,"jpg",file);
  }
 catch (  IOException e) {
    e.printStackTrace();
  }
  rendImage=drawAltitudeGraph(c);
  file=new File("Altitude.jpg");
  try {
    ImageIO.write(rendImage,"jpg",file);
  }
 catch (  IOException e) {
    e.printStackTrace();
  }
  rendImage=drawSpeedGraph(c);
  file=new File("Speed.jpg");
  try {
    ImageIO.write(rendImage,"jpg",file);
  }
 catch (  IOException e) {
    e.printStackTrace();
  }
}
 

Example 76

From project jena-examples, under directory /src/main/java/org/apache/jena/examples/.

Source file: ExampleJenaJUNG_01.java

  15 
vote

public static void main(String[] args){
  FileManager fm=FileManager.get();
  fm.addLocatorClassLoader(ExampleJenaJUNG_01.class.getClassLoader());
  Model model=fm.loadModel("data/data.nt");
  Graph<RDFNode,Statement> g=new JenaJungGraph(model);
  Layout<RDFNode,Statement> layout=new FRLayout<RDFNode,Statement>(g);
  int width=1400;
  int height=800;
  layout.setSize(new Dimension(width,height));
  VisualizationImageServer<RDFNode,Statement> viz=new VisualizationImageServer<RDFNode,Statement>(layout,new Dimension(width,height));
  RenderContext<RDFNode,Statement> context=viz.getRenderContext();
  context.setEdgeLabelTransformer(Transformers.EDGE);
  context.setVertexLabelTransformer(Transformers.NODE);
  viz.setPreferredSize(new Dimension(width,height));
  Image img=viz.getImage(new Point(width / 2,height / 2),new Dimension(width,height));
  BufferedImage bi=new BufferedImage(width,height,BufferedImage.TYPE_INT_RGB);
  Graphics2D g2d=bi.createGraphics();
  g2d.setColor(Color.white);
  g2d.fillRect(0,0,width,height);
  g2d.setColor(Color.white);
  g2d.drawImage(img,0,0,width,height,Color.blue,null);
  try {
    ImageIO.write(bi,"PNG",new File("/tmp/graph.png"));
    System.out.println("Image saved");
  }
 catch (  IOException ex) {
    ex.printStackTrace(System.err);
  }
}
 

Example 77

From project jforum2, under directory /src/net/jforum/util/.

Source file: Captcha.java

  15 
vote

public void writeCaptchaImage(){
  BufferedImage image=SessionFacade.getUserSession().getCaptchaImage();
  if (image == null) {
    return;
  }
  OutputStream outputStream=null;
  try {
    outputStream=JForumExecutionContext.getResponse().getOutputStream();
    ImageIO.write(image,"jpg",outputStream);
  }
 catch (  IOException ex) {
    logger.error(ex);
  }
 finally {
    if (outputStream != null) {
      try {
        outputStream.close();
      }
 catch (      IOException ex) {
      }
    }
  }
}