jpg 真彩无损压缩格式,网络上图像一般都jpg png 真彩无操损压缩格式,支持画布透明 gif 颜色不能超过256种颜色,所以此格式不是真彩,既支持帧静态图像,又支持多帧动态图像,是图像 文件中唯一支持动画的
public static void main(String[] args) throws IOException { //创建画板,1为jpg格式,2为png格式在后面再增加一个参数为透明度 BufferedImage i = new BufferedImage(800, 800, 1); //创建画笔 var m = i.createGraphics(); //设置平滑度 m.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_GASP); m.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); m.setRenderingHint(RenderingHints.KEY_STROKE_CONTROL, RenderingHints.VALUE_STROKE_DEFAULT); //设置画笔颜色 m.setColor(Color.ORANGE); //fill为填充,fillRect填充矩形 m.fillRect(0, 0, 800, 800); m.setColor(Color.WHITE); //m.drawArc(200, 200, 200, 200, 0, 90); //填充圆弧,画半圆 m.fillArc(150, 150, 500, 500, 90, 180); m.setColor(Color.BLACK); m.fillArc(150, 150, 500, 500, -90, 180); m.setColor(Color.WHITE); m.fillArc(275, 150, 250, 250, -90, 180); m.setColor(Color.BLACK); m.fillArc(275, 400, 250, 250, 90, 180); m.setColor(Color.BLACK); m.fillOval(350, 225, 100, 100); m.setColor(Color.WHITE); //椭圆 m.fillOval(350, 475, 100, 100); //关闭 m.dispose(); //画板写入文件 ImageIO.write(i, "png", new File("taiji.png")); //系统运行打开图片 Runtime.getRuntime().exec("cmd /k start taiji.png"); }
水印操作
public static void main(String[] args) throws IOException { BufferedImage i = new BufferedImage(800, 800, 1); var m = i.createGraphics(); //设置抗锯齿(平滑度) m.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_GASP); m.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); m.setRenderingHint(RenderingHints.KEY_STROKE_CONTROL, RenderingHints.VALUE_STROKE_DEFAULT); m.setColor(Color.YELLOW); m.fillRect(0, 0, 800, 800); m.setColor(Color.BLACK); //虚线 for (int j = 0; j < 100; j++) { int x = j * 10 + 5; int x1 = j * 10 + 10; int y = 400; m.drawLine(x, y, x1, y); } for (int j = 0; j < 100; j++) { int x = j * 10 + 5; int x1 = j * 10 + 10; int y = 400; m.drawLine(y, x, y, x1); } m.setColor(Color.red); //文字设置 Font font = new Font("微软雅黑", Font.BOLD, 30); m.setFont(font); String text = "此版权-陈卸甲"; var fm = m.getFontMetrics(font); var tw = fm.stringWidth(text); var th = fm.getHeight(); //Ascent是baseline之上至字符最高处的距离,Descent是baseline之下至字符最低处的距离 m.drawString(text, i.getWidth() / 2 - tw / 2, i.getHeight() / 2 + (fm.getAscent() - fm.getDescent()) / 2); m.drawString(text, i.getWidth() - tw - 10, i.getHeight() - fm.getDescent() - 10); m.drawString(text, 10, fm.getAscent() + 10); m.dispose(); ImageIO.write(i, "jpg", new File("strimg.jpg")); Runtime.getRuntime().exec("cmd /k start strimg.jpg"); }