javax.imageio.ImageIO.write()方法的使用及代码示例

x33g5p2x  于2022-01-20 转载在 其他  
字(10.9k)|赞(0)|评价(0)|浏览(1808)

本文整理了Java中javax.imageio.ImageIO.write()方法的一些代码示例,展示了ImageIO.write()的具体用法。这些代码示例主要来源于Github/Stackoverflow/Maven等平台,是从一些精选项目中提取出来的代码,具有较强的参考意义,能在一定程度帮忙到你。ImageIO.write()方法的具体详情如下:
包路径:javax.imageio.ImageIO
类名称:ImageIO
方法名:write

ImageIO.write介绍

暂无

代码示例

代码示例来源:origin: plantuml/plantuml

public boolean saveToImage(String pFileName, String pFormat) throws IOException {
  return ImageIO.write(fEarthImage2, pFormat, new File(pFileName));
}

代码示例来源:origin: igniterealtime/Smack

@Override
  public ByteArrayOutputStream encode(BufferedImage bufferedImage) {
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    try {
      ImageIO.write(bufferedImage, "png", baos);
    }
    catch (IOException e) {
      LOGGER.log(Level.WARNING, "exception", e);
      baos = null;
    }
    return baos;
  }
}

代码示例来源:origin: plantuml/plantuml

private byte[] writeImageToBytes(Image image) throws IOException
{
  BufferedImage bi = new BufferedImage(width, height,BufferedImage.TYPE_INT_RGB);
  ByteArrayOutputStream baos = new ByteArrayOutputStream();
  Graphics2D g = bi.createGraphics();
  g.drawImage(image,0,0,width,height,null);
  ImageIO.write(bi,"jpg",baos);
  baos.close();
  bi = null;
  g = null;
  
  return baos.toByteArray();
}

代码示例来源:origin: stanfordnlp/CoreNLP

private void doExportTree() {
 JFileChooser chooser = new JFileChooser();
 chooser.setSelectedFile(new File("./tree.png"));
 FileNameExtensionFilter filter = new FileNameExtensionFilter("PNG images", "png");
 chooser.setFileFilter(filter);
 int status = chooser.showSaveDialog(this);
 if (status != JFileChooser.APPROVE_OPTION)
  return;
 Dimension size = tjp.getPreferredSize();
 BufferedImage im = new BufferedImage((int) size.getWidth(),
                    (int) size.getHeight(),
                    BufferedImage.TYPE_INT_ARGB);
 Graphics2D g = im.createGraphics();
 tjp.paint(g);
 try {
  ImageIO.write(im, "png", chooser.getSelectedFile());
 } catch (IOException e) {
  JOptionPane.showMessageDialog(this, "Failed to save the tree image file.\n"
                 + e.getLocalizedMessage(), "Export Error",
                 JOptionPane.ERROR_MESSAGE);
 }
}

代码示例来源:origin: twosigma/beakerx

/**
 * Converts the given {@link RenderedImage} into a stream of bytes.
 *
 * @param image The image to convert to a byte stream.
 * @param format The informal name of the format for the returned bytes; e.g.
 *        "png" or "jpg". See {@link ImageIO#getImageWritersByFormatName(String)}.
 * @return A stream of bytes in the requested format, or null if the
 *         image cannot be converted to the specified format.
 */
public static byte[] encode(RenderedImage image, String format)
 throws IOException
{
 ByteArrayOutputStream baos = new ByteArrayOutputStream();
 boolean success = ImageIO.write(image, format, baos);
 return success ? baos.toByteArray() : null;
}

代码示例来源:origin: stackoverflow.com

BufferedImage image = new BufferedImage(
    sz, sz, BufferedImage.TYPE_INT_ARGB);
Graphics2D g = image.createGraphics();
g.setRenderingHint(
    RenderingHints.KEY_ANTIALIASING,
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ImageIO.write(image, "png", baos);
System.out.println("baos.toByteArray() " + baos.toByteArray());
System.out.println("baos.toByteArray().length " + baos.toByteArray().length);
String data = DatatypeConverter.printBase64Binary(baos.toByteArray());
String imageString = "data:image/png;base64," + data;
String html =
File f = new File("image.html");
FileWriter fw = new FileWriter(f);
fw.write(html);

代码示例来源:origin: haraldk/TwelveMonkeys

public static void main(String[] args) throws IOException {
    BufferedImage image = ImageIO.read(new File(args[0]));
    ImageIO.write(image, "TGA", new File("foo.tga"));
  }
}

代码示例来源:origin: libgdx/libgdx

input = ImageIO.read(new File(inputFile));
} catch (IOException e) {
  System.err.println("Failed to load image: " + e.getMessage());
  ImageIO.write(output, outputFormat, new File(outputFile));
} catch (IOException e) {
  System.err.println("Failed to write output image: " + e.getMessage());

代码示例来源:origin: plantuml/plantuml

private boolean renderToPNG(Diagram diagram, String filename, RenderingOptions options){	
  RenderedImage image = renderToImage(diagram, options);
  
  try {
    File file = new File(filename);
    ImageIO.write(image, "png", file);
  } catch (IOException e) {
    //e.printStackTrace();
    System.err.println("Error: Cannot write to file "+filename);
    return false;
  }
  return true;
}

代码示例来源:origin: primefaces/primefaces

File file = new File(externalContext.getRealPath("") + imagePath);
    inputStream = new FileInputStream(file);
BufferedImage outputImage = ImageIO.read(inputStream);
  w = outputImage.getWidth() - x;
if (y + h > outputImage.getHeight()) {
  h = outputImage.getHeight() - y;
ByteArrayOutputStream croppedOutImage = new ByteArrayOutputStream();
String format = guessImageFormat(contentType, imagePath);
ImageIO.write(cropped, format, croppedOutImage);
return new CroppedImage(cropper.getImage(), croppedOutImage.toByteArray(), x, y, w, h);

代码示例来源:origin: signalapp/BitHub

public static byte[] createFor(String price) throws IOException {
 byte[]        badgeBackground = Resources.toByteArray(Resources.getResource("assets/badge.png"));
 BufferedImage bufferedImage   = ImageIO.read(new ByteArrayInputStream(badgeBackground));
 Graphics2D    graphics        = bufferedImage.createGraphics();
 graphics.setFont(new Font("OpenSans", Font.PLAIN, 34));
 graphics.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING,
              RenderingHints.VALUE_TEXT_ANTIALIAS_LCD_HRGB);
 graphics.drawString(price + " USD", 86, 45);
 graphics.dispose();
 ByteArrayOutputStream baos = new ByteArrayOutputStream();
 ImageIO.write(bufferedImage, "png", baos);
 return baos.toByteArray();
}

代码示例来源:origin: MovingBlocks/Terasology

public static void convertFileToTexture() throws IOException {
    float[][] heightmap = readFile();

    double scaleFactor = 256 * 256 * 12.8;

//        Slick's PNGDecoder does not support 16 bit textures

//        BufferedImage image = new BufferedImage(512, 512, BufferedImage.TYPE_USHORT_GRAY);
//        DataBufferUShort buffer = (DataBufferUShort) image.getRaster().getDataBuffer();
//        scaleFactor *= 256.0f;

//        Slick's PNGDecoder does not support grayscale textures

//        BufferedImage image = new BufferedImage(512, 512, BufferedImage.TYPE_BYTE_GRAY);
//        DataBufferByte buffer = (DataBufferByte) image.getRaster().getDataBuffer();

    BufferedImage image = new BufferedImage(512, 512, BufferedImage.TYPE_INT_RGB);
    DataBufferInt buffer = (DataBufferInt) image.getRaster().getDataBuffer();

    for (int x = 0; x < 512; x++) {
      for (int z = 0; z < 512; z++) {
        double doubleVal = heightmap[x][z] * scaleFactor;
        int val = DoubleMath.roundToInt(doubleVal, RoundingMode.HALF_UP);
        buffer.setElem(z * 512 + x, val);
      }
    }

    ImageIO.write(image, "png", new File("platec_heightmap.png"));
  }

代码示例来源:origin: vert-x3/vertx-examples

public Image(Vertx vertx, String name) {
 try {
  final BufferedImage raster = ImageIO.read(((VertxInternal) vertx).resolveFile(name));
  width = raster.getWidth();
  height = raster.getHeight();
  data = raster.getRGB(0, 0, width, height, null, 0, width);
  for (int pixel : data)
   if (!colorMap.containsKey(pixel)) {
    BufferedImage offlineImage = new BufferedImage(1, 1, BufferedImage.TYPE_INT_ARGB);
    Graphics2D g2 = offlineImage.createGraphics();
    g2.setPaint(new Color(pixel, true));
    g2.fillRect(0, 0, 1, 1);
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    ImageIO.write(offlineImage, "PNG", out);
    colorMap.put(pixel, Buffer.buffer().appendBytes(out.toByteArray()));
    out.close();
    g2.dispose();
   }
 } catch (IOException e) {
  throw new RuntimeException(e);
 }
}

代码示例来源:origin: looly/hutool

int srcHeight = bi.getHeight(); // 源图高度
    tag = cut(bi, new Rectangle(j * destWidth, i * destHeight, destWidth, destHeight));
    ImageIO.write(tag, IMAGE_TYPE_JPEG, new File(destDir, "_r" + i + "_c" + j + ".jpg"));

代码示例来源:origin: opentripplanner/OpenTripPlanner

@GET @Path("/tile/{layer}/{z}/{x}/{y}.{ext}")
@Produces("image/*")
public Response tileGet() throws Exception {
  // Re-use analyst
  Envelope2D env = SlippyTile.tile2Envelope(x, y, z);
  TileRequest tileRequest = new TileRequest(env, 256, 256);
  Router router = otpServer.getRouter(routerId);
  BufferedImage image = router.tileRendererManager.renderTile(tileRequest, layer);
  MIMEImageFormat format = new MIMEImageFormat("image/" + ext);
  ByteArrayOutputStream baos = new ByteArrayOutputStream(image.getWidth() * image.getHeight() / 4);
  ImageIO.write(image, format.type, baos);
  CacheControl cc = new CacheControl();
  cc.setMaxAge(3600);
  cc.setNoCache(false);
  return Response.ok(baos.toByteArray()).type(format.toString()).cacheControl(cc).build();
}

代码示例来源:origin: libgdx/libgdx

private void generatePremultiplyAlpha(File out){
  try {
    BufferedImage outImage = new BufferedImage(image.getWidth(), image.getHeight(), BufferedImage.TYPE_INT_ARGB);
    float[] color = new float[4];
    WritableRaster raster = image.getRaster();
    WritableRaster outRaster = outImage.getRaster();
    for(int x =0, w = image.getWidth(); x< w; ++x)
      for(int y =0, h = image.getHeight(); y< h; ++y){
        raster.getPixel(x, y, color);
        float alpha = color[3]/255f;
        for(int i=0;i < 3; ++i) 
          color[i] *= alpha;
        outRaster.setPixel(x, y, color);
      }
    ImageIO.write(outImage, "png", out);
  } catch (IOException e) {
    e.printStackTrace();
  }
}

代码示例来源:origin: jfinal/jfinal

public void render() {
  BufferedImage image = new BufferedImage(WIDTH, HEIGHT, BufferedImage.TYPE_INT_RGB);
  String vCode = drawGraphic(image);
  vCode = vCode.toUpperCase();
  vCode = HashKit.md5(vCode);
  Cookie cookie = new Cookie(captchaName, vCode);
  cookie.setMaxAge(-1);
  cookie.setPath("/");
  // cookie.setHttpOnly(true);
  response.addCookie(cookie);
  response.setHeader("Pragma","no-cache");
  response.setHeader("Cache-Control","no-cache");
  response.setDateHeader("Expires", 0);
  response.setContentType("image/jpeg");
  
  ServletOutputStream sos = null;
  try {
    sos = response.getOutputStream();
    ImageIO.write(image, "jpeg",sos);
  } catch (Exception e) {
    throw new RuntimeException(e);
  }
  finally {
    if (sos != null) {
      try {sos.close();} catch (IOException e) {LogKit.logNothing(e);}
    }
  }
}

代码示例来源:origin: apache/nifi

scaledBufferedImg = new BufferedImage(scaledImage.getWidth(null), scaledImage.getHeight(null), imageType);
  final Graphics2D graphics = scaledBufferedImg.createGraphics();
  try {
    graphics.drawImage(scaledImage, 0, 0, null);
ImageIO.write(scaledBufferedImg, formatName, out);

代码示例来源:origin: hs-web/hsweb-framework

@GetMapping("/{processInstanceId}/image")
  @ApiOperation("查看当前流程活动节点流程图")
  @Authorize(action = Permission.ACTION_QUERY)
  public void getProcessImage(@PathVariable String processInstanceId, HttpServletResponse response) throws IOException {
    try (InputStream inputStream = bpmProcessService.findProcessPic(processInstanceId)) {
      response.setContentType(MediaType.IMAGE_PNG_VALUE);
      ImageIO.write(ImageIO.read(inputStream), "png", response.getOutputStream());
    }
  }
}

代码示例来源:origin: skylot/jadx

public void decode(InputStream in, OutputStream out) throws JadxException {
  try {
    byte[] data = IOUtils.toByteArray(in);
    BufferedImage im = ImageIO.read(new ByteArrayInputStream(data));
    int w = im.getWidth();
    int h = im.getHeight();
    BufferedImage im2 = new BufferedImage(w + 2, h + 2, BufferedImage.TYPE_INT_ARGB);
    im2.createGraphics().drawImage(im, 1, 1, w, h, 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 | NullPointerException ex) {
    throw new JadxException(ex.toString());
  }
}

相关文章