Java Code Examples for javax.imageio.ImageIO.write()

The following are Jave code examples for showing how to use write() of the javax.imageio.ImageIO class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
+ Save this method
Example 1
Project: sumo   File: Font.java   View Source Code Vote up 6 votes
public void writeFontData(String textureFilename, String descriptionFilename) throws IOException
{
	ImageIO.write(image, "png", new File(textureFilename));
	
	StringBuilder buffer = new StringBuilder();
	
	buffer.append("<?xml version='1.0' encoding='utf-8'?>\n\n");
	buffer.append("<!--  Keep in mind that pixmaps have their origin in the upper left corner! -->\n\n");

	buffer.append("<Font>\n");
	
	for(Character c: texHashMap.keySet())
	{
		CharacterPixmap pixmap = texHashMap.get(c);

		pixmap.toXML("  ", buffer);
	}
	buffer.append("</Font>");
	FileOutputStream fileOut = new FileOutputStream(descriptionFilename, false);
	OutputStreamWriter out = new OutputStreamWriter(fileOut, "UTF-8");
	System.out.println("Writing description file with encoding "+out.getEncoding());
	out.write(buffer.toString());
	out.close();
}
 
Example 2
Project: org.alloytools.alloy   File: OurPNGWriter.java   View Source Code Vote up 6 votes
/**
 * Writes the image as a PNG file with the given horizontal and vertical
 * dots-per-inch.
 */
public static void writePNG(BufferedImage image, String filename, double dpiX, double dpiY) throws IOException {
	try {
		ImageIO.write(image, "PNG", new File(filename)); // some versions of
															// Java
															// sometimes
															// throws an
															// exception
															// during
															// saving...
		setDPI(filename, dpiX, dpiY);
	} catch (Throwable ex) {
		if (ex instanceof IOException)
			throw (IOException) ex;
		if (ex instanceof StackOverflowError)
			throw new IOException("Out of memory trying to save the PNG file to " + filename);
		if (ex instanceof OutOfMemoryError)
			throw new IOException("Out of memory trying to save the PNG file to " + filename);
		throw new IOException("Error writing the PNG file to " + filename + " (" + ex + ")");
	}
}
 
Example 3
Project: CyberSecurity   File: PictureEdit.java   View Source Code Vote up 6 votes
/**
	 * Saves a file by opening a JFileChooser which allows the user to select
	 * the file they would like to save over or create a new file to save onto.
	 *
	 * @return true if the file successfully opened, false otherwise.
	 */

	public boolean saveAs()
	{
 	JFileChooser chooser = new JFileChooser(".");
    int returnVal = chooser.showSaveDialog(null);
    if(returnVal == JFileChooser.APPROVE_OPTION) {
		try{
		ImageIO.write(image, "png",chooser.getSelectedFile());
		}
		catch(Exception e){
			return false;
		}
		return true;
    }
    return false;

}
 
Example 4
Project: enhanced-vnc-thumbnail-viewer   File: VncCanvas.java   View Source Code Vote up 6 votes
public void capture() {
    synchronized (memImage) {
        imageUpdate(memImage, -1, 0, 0, rfb.framebufferWidth, rfb.framebufferHeight);
        BufferedImage image = new BufferedImage(rfb.framebufferWidth, rfb.framebufferHeight, BufferedImage.TYPE_INT_RGB);
        Graphics2D g2 = image.createGraphics();
        g2.drawImage(memImage, 0, 0, rfb.framebufferWidth, rfb.framebufferHeight, null);
        g2.dispose();

        try {
            Calendar c = Calendar.getInstance();
            ImageIO.write(image, "jpg", new File(manageScreenPath(ScreenCaptureSetting.getPath()) +
                    manageScreenName(viewer.compname) + "_" + 
                    c.get(Calendar.YEAR) + "-" + 
                    addZeroOnDateTime(c.get(Calendar.MONTH) + 1) + "-" + 
                    addZeroOnDateTime(c.get(Calendar.DATE)) + "_" + 
                    addZeroOnDateTime(c.get(Calendar.HOUR_OF_DAY)) + "-" + 
                    addZeroOnDateTime(c.get(Calendar.MINUTE)) + "-" + 
                    addZeroOnDateTime(c.get(Calendar.SECOND)) + 
                    ".jpg"));
            
            System.out.println("Captured screen: "+ viewer.compname);
        } catch (IOException ex) {
        }
    }
}
 
Example 5
Project: SE2017-Team1   File: TestUtil.java   View Source Code Vote up 5 votes
public static void exportToImage(String format, JPanel dPanel, String fileName) {
  BufferedImage bImg = new BufferedImage(dPanel.getWidth(), dPanel.getHeight(), BufferedImage.TYPE_INT_RGB);
  Graphics2D cg = bImg.createGraphics();
  dPanel.paintAll(cg);
  try {
          if (ImageIO.write(bImg, "jpg", new File("./" + fileName + "." + format)))
          {
              System.out.println("image saved succesfully");
          }
  } catch (IOException e) {
          // TODO Auto-generated catch block
          e.printStackTrace();
  }
}
 
Example 6
Project: jdk8u-jdk   File: GenerateTestImage.java   View Source Code Vote up 5 votes
public static void main(String[] args) throws Exception {
    String path = System.getProperty("test.classes") + File.separator + "test.png";

    BufferedImage image = new BufferedImage(IMAGE_SIZE, IMAGE_SIZE, BufferedImage.TYPE_INT_ARGB);
    Graphics2D graphics2D = image.createGraphics();
    graphics2D.setColor(Color.red);
    graphics2D.fillOval(0, 0, IMAGE_SIZE, IMAGE_SIZE);
    graphics2D.dispose();;

    try(FileOutputStream fos = new FileOutputStream(path)) {
        ImageIO.write(image, "png", fos);
    }
}
 
Example 7
Project: openjdk-jdk10   File: TransformedPaintTest.java   View Source Code Vote up 5 votes
private void checkBI(BufferedImage bi) {
    for (int y = 0; y < bi.getHeight(); y++) {
        for (int x = 0; x < bi.getWidth(); x++) {
            if (bi.getRGB(x, y) == Color.blue.getRGB()) {
                try {
                    String fileName = "TransformedPaintTest_res.png";
                    ImageIO.write(bi, "png", new File(fileName));
                    System.err.println("Dumped image to: " + fileName);
                } catch (IOException ex) {}
                throw new RuntimeException("Test failed, blue color found");
            }
        }
    }
}
 
Example 8
Project: OnlineElectionVotingSystem   File: CaptchaServlet.java   View Source Code Vote up 5 votes
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
	int width = 155;
	int height = 50;
	BufferedImage buf = new BufferedImage(width,height, BufferedImage.TYPE_INT_RGB);
	HttpSession session=request.getSession();
	Graphics2D g = buf.createGraphics();    // creating Graphics2D
	GradientPaint gp = new GradientPaint(0,0,Color.orange, 0, height/2, Color.GREEN, true); // mixing of 2 colors
	
	g.setPaint(gp);
	Font f = new Font("Times New Roman", Font.BOLD, 22);
	g.setFont(f);
	g.fillRect(0, 0, width, height);
	g.setColor(new Color(0,153,255));
	
	String data = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
	String captcha = "";
	String captcha1="";
	char ch[] = data.toCharArray();
	for (int i=0; i<6; i++)
	{
		int j = (int)((Math.random()) * 62);
		captcha = captcha +" "+ch[j];
		captcha1 = captcha1+ch[j];
	}
	session.setAttribute("captcha", captcha1); 	// captcha  is name & captcha1 is value 
	g.drawString(captcha, 10, 35);
	g.dispose();
	response.setContentType("image/png");
	OutputStream os = response.getOutputStream();
	ImageIO.write(buf , "png",os);
	
}
 
Example 9
Project: opencron   File: ImageUtils.java   View Source Code Vote up 5 votes
public boolean build(){
    String imageType = getFileType(originImage.getName());
    try {
        ImageIO.write(dealedImage,imageType,originImage);
        return true;
    } catch (IOException e) {
        e.printStackTrace();
    }
    return false;
}
 
Example 10
Project: openjdk-jdk10   File: MultiResolutionSplashTest.java   View Source Code Vote up 5 votes
static void generateImage(String name, Color color, float scale) throws Exception {
    File file = new File(name);
    if (file.exists()) {
        return;
    }
    BufferedImage image = new BufferedImage((int) (scale * IMAGE_WIDTH),
            (int) (scale * IMAGE_HEIGHT), BufferedImage.TYPE_INT_RGB);
    Graphics g = image.getGraphics();
    g.setColor(color);
    g.fillRect(0, 0, (int) (scale * IMAGE_WIDTH), (int) (scale * IMAGE_HEIGHT));
    ImageIO.write(image, "png", file);
}
 
Example 11
Project: parabuild-ci   File: SunPNGEncoderAdapter.java   View Source Code Vote up 5 votes
/**
 * Encodes an image in PNG format and writes it to an OutputStream.
 *
 * @param bufferedImage  The image to be encoded.
 * @param outputStream  The OutputStream to write the encoded image to.
 * @throws IOException
 */
public void encode(BufferedImage bufferedImage, OutputStream outputStream) 
    throws IOException {
    if (bufferedImage == null) {
        throw new IllegalArgumentException("Null 'image' argument.");
    }
    if (outputStream == null) {
        throw new IllegalArgumentException("Null 'outputStream' argument.");
    }
    ImageIO.write(bufferedImage, ImageFormat.PNG, outputStream);
}
 
Example 12
Project: DWSurvey   File: TwoDimensionCode.java   View Source Code Vote up 5 votes
/**
 * 生成二维码(QRCode)图片
 * @param content 存储内容
 * @param output 输出流
 * @param imgType 图片类型
 * @param size 二维码尺寸
 */
public void encoderQRCode(String content, OutputStream output, String imgType, int size) {
	try {
		BufferedImage bufImg = this.qRCodeCommon(content, imgType, size);
		// 生成二维码QRCode图片
		ImageIO.write(bufImg, imgType, output);
	} catch (Exception e) {
		e.printStackTrace();
	}
}
 
Example 13
Project: jdk8u-jdk   File: MisplacedBorder.java   View Source Code Vote up 5 votes
@Override
public void run() {
    final JMenuBar menubar = new JMenuBar();
    menubar.add(new JMenu(""));
    menubar.add(new JMenu(""));
    final JFrame frame = new JFrame();
    frame.setUndecorated(true);
    frame.setJMenuBar(menubar);
    frame.setSize(W / 3, H / 3);
    frame.setLocationRelativeTo(null);
    frame.setVisible(true);

    // draw menu bar using standard order.
    final BufferedImage bi1 = step1(menubar);

    // draw menu border on top of the menu bar, nothing should be changed.
    final BufferedImage bi2 = step2(menubar);
    frame.dispose();

    for (int x = 0; x < W; ++x) {
        for (int y = 0; y < H; ++y) {
            if (bi1.getRGB(x, y) != bi2.getRGB(x, y)) {
                try {
                    ImageIO.write(bi1, "png", new File("image1.png"));
                    ImageIO.write(bi2, "png", new File("image2.png"));
                } catch (IOException e) {
                    e.printStackTrace();
                }
                throw new RuntimeException("Failed: wrong color");
            }
        }
    }
}
 
Example 14
Project: openjdk-jdk10   File: ConcurrentReadingTest.java   View Source Code Vote up 5 votes
private static void createTestFile() {
    int w = 1280;
    int h = 1024;

    BufferedImage img = new
        BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
    Graphics2D g = img.createGraphics();
    Color[] colors = { Color.red, Color.green, Color.blue };
    float[] dist = {0.0f, 0.5f, 1.0f };
    Point2D center = new Point2D.Float(0.5f * w, 0.5f * h);

    RadialGradientPaint p =
        new RadialGradientPaint(center, 0.5f * w, dist, colors);
    g.setPaint(p);
    g.fillRect(0, 0, w, h);
    g.dispose();

    try {
        System.out.println("Create test image " + file.getAbsolutePath());
        boolean b = ImageIO.write(img, "JPEG", file);
        if (!b) {
            throw new RuntimeException("Failed to create test image.");
        }
    } catch (IOException e) {
        throw new RuntimeException("Test failed", e);
    }
}
 
Example 15
Project: mumu   File: RcCaptchaFilter.java   View Source Code Vote up 4 votes
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
	//int width = 57;// 图像宽度
	//int height = 21;// 图像高度
	int width = 80;// 图像宽度
	int height = 40;// 图像高度
	// 定义输出格式
	response.setContentType("image/jpeg");
	ServletOutputStream out = response.getOutputStream();
	// 准备缓冲图像,不支持表单
	BufferedImage bimg = new BufferedImage(width, height, BufferedImage.TYPE_INT_BGR);
	Random r = new Random();
	// 获取图形上下文环境
	Graphics gc = bimg.getGraphics();
	// 设定背景色并进行填充
	gc.setColor(getRandColor(200, 250));
	gc.fillRect(0, 0, width, height);
	// 设置图形上下文环境字体
	gc.setFont(new Font("Times New Roman", Font.PLAIN, 20));
	// 随机产生200条干扰线条,使图像中的认证码不易被其他分析程序探测到
	gc.setColor(getRandColor(160, 200));
	for (int i = 0; i < 200; i++) {
		int x1 = r.nextInt(width);
		int y1 = r.nextInt(height);
		int x2 = r.nextInt(15);
		int y2 = r.nextInt(15);
		gc.drawLine(x1, y1, x1 + x2, y1 + y2);
	}
	// 随机产生100个干扰点,使图像中的验证码不易被其他分析程序探测到
	gc.setColor(getRandColor(120, 240));
	for (int i = 0; i < 100; i++) {
		int x = r.nextInt(width);
		int y = r.nextInt(height);
		gc.drawOval(x, y, 0, 0);
	}

	// 随机产生4个数字的验证码
	String rs = "";
	String rn = "";
	for (int i = 0; i < 4; i++) {
		rn = String.valueOf(r.nextInt(10));
		rs += rn;
		gc.setColor(new Color(20 + r.nextInt(110), 20 + r.nextInt(110), 20 + r.nextInt(110)));
		gc.drawString(rn, 20 * i + 6, 27);
	}

	// 释放图形上下文环境
	gc.dispose();

	request.getSession().setAttribute("rcCaptcha", rs);
	ImageIO.write(bimg, "jpeg", out);
	try {
		out.flush();
	} finally {
		out.close();
	}
}
 
Example 16
Project: rure   File: CaptchaUtil.java   View Source Code Vote up 4 votes
public void write(OutputStream sos) throws IOException {
	ImageIO.write(buffImg, "png", sos);
	sos.close();
}
 
Example 17
Project: wish-pay   File: ZxingUtils.java   View Source Code Vote up 4 votes
private static void writeToFile(BitMatrix matrix, String format, File file) throws IOException {
    BufferedImage image = toBufferedImage(matrix);
    if (!ImageIO.write(image, format, file)) {
        throw new IOException("Could not write an image of format " + format + " to " + file);
    }
}
 
Example 18
Project: openjdk-jdk10   File: CrashNaNTest.java   View Source Code Vote up 4 votes
private static void testDrawComplexAt() {
    final int width = 400;
    final int height = 400;

    final BufferedImage image = new BufferedImage(width, height,
                                        BufferedImage.TYPE_INT_ARGB);

    final Graphics2D g2d = (Graphics2D) image.getGraphics();
    try {
        g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
                             RenderingHints.VALUE_ANTIALIAS_ON);
        g2d.setRenderingHint(RenderingHints.KEY_STROKE_CONTROL,
                             RenderingHints.VALUE_STROKE_PURE);

        g2d.setBackground(Color.WHITE);
        g2d.clearRect(0, 0, width, height);

        final Path2D.Double path = new Path2D.Double();
        path.moveTo(100, 100);

        for (int i = 0; i < 20000; i++) {
            path.lineTo(110 + 0.01 * i, 110);
            path.lineTo(111 + 0.01 * i, 100);
        }

        path.lineTo(NaN, 200);
        path.lineTo(200, 200);
        path.lineTo(200, NaN);
        path.lineTo(300, 300);
        path.lineTo(NaN, NaN);
        path.lineTo(100, 200);
        path.closePath();

        final Path2D.Double path2 = new Path2D.Double();
        path2.moveTo(0, 0);
        path2.lineTo(100, height);
        path2.lineTo(0, 200);
        path2.closePath();

        // Define an non-uniform transform:
        g2d.scale(0.5, 1.0);
        g2d.rotate(Math.PI / 31);

        g2d.setColor(Color.BLACK);
        g2d.draw(path);
        g2d.draw(path2);

        if (SAVE_IMAGE) {
            try {
                final File file = new File("CrashNaNTest-draw.png");
                System.out.println("Writing file: "
                                   + file.getAbsolutePath());
                ImageIO.write(image, "PNG", file);
            } catch (IOException ex) {
                System.out.println("Writing file failure:");
                ex.printStackTrace();
            }
        }

        // Check image on few pixels:
        final Raster raster = image.getData();

        checkPixelNotWhite(raster, 40, 210);
        checkPixelNotWhite(raster, 44, 110);
        checkPixelNotWhite(raster, 60, 120);
        checkPixelNotWhite(raster, 89, 219);
        checkPixelNotWhite(raster, 28, 399);
        checkPixelNotWhite(raster, 134, 329);

    } finally {
        g2d.dispose();
    }
}
 
Example 19
Project: jdk8u-jdk   File: OutputImageTests.java   View Source Code Vote up 4 votes
void initContents(File f) throws IOException {
    ImageIO.write(image, format, f);
}
 
Example 20
Project: os   File: MatrixToImageWriterEx.java   View Source Code Vote up 3 votes
/**
 * 将照片添加到二维码中间,并生成流
 * @author:chenming
 * @date:2014年12月31日
 *
 * @param matrix 要写入的二维码
 * @param formate 照片格式
 * @param logoPath	要写入照片的路径
 * @param logoConfig logo配置对象  可以为null,为 null 默认 DEFAULT_CONFIG
 * @throws java.io.IOException
 */
public static void overlapImage(BitMatrix matrix,String formate,String logoPath,MatrixToLogoImageConfig logoConfig,OutputStream out) throws IOException{
	//将matrix转换为bufferImage
	BufferedImage image = MatrixToImageWriter.toBufferedImage(matrix);
	
	//将logo照片绘制到二维码中间
	drawImage(logoPath, image, logoConfig);
	
	//输出
	ImageIO.write(image, formate, out);
}