Example usage for java.awt.image BufferedImage BufferedImage

List of usage examples for java.awt.image BufferedImage BufferedImage

Introduction

In this page you can find the example usage for java.awt.image BufferedImage BufferedImage.

Prototype

public BufferedImage(int width, int height, int imageType) 

Source Link

Document

Constructs a BufferedImage of one of the predefined image types.

Usage

From source file:com.liusoft.dlog4j.util.ImageUtils.java

/**
 * ?//from  w  w  w.  ja  va2s . com
 * @param orig_img
 * @param obj_filename
 * @param p_width
 * @param p_height
 * @throws IOException
 */
public static String createPreviewImage(InputStream orig_img, String obj_filename, int p_width, int p_height)
        throws IOException {
    String extendName = StringUtils.getFileExtend(obj_filename).toLowerCase();

    FileOutputStream newimage = null;
    InputStream fis = orig_img;
    try {
        if ("gif".equalsIgnoreCase(extendName)) {
            GifImage gifImage = GifDecoder.decode(fis);
            fis.close();
            fis = null;
            GifImage newGif = GifTransformer.resize(gifImage, p_width, p_height, false);
            newimage = new FileOutputStream(obj_filename);
            GifEncoder.encode(newGif, newimage);
        } else {
            BufferedImage orig_portrait = (BufferedImage) ImageIO.read(fis);
            fis.close();
            fis = null;
            // ?JPG?
            BufferedImage bi = new BufferedImage(p_width, p_height, BufferedImage.TYPE_INT_RGB);
            bi.getGraphics().drawImage(orig_portrait, 0, 0, p_width, p_height, null);
            if (!obj_filename.endsWith(".jpg"))
                obj_filename += ".jpg";
            newimage = new FileOutputStream(obj_filename);
            ImageIO.write(bi, "jpg", newimage);
        }
    } finally {
        if (newimage != null)
            newimage.close();
        if (fis != null)
            fis.close();
    }
    return obj_filename;
}

From source file:net.sf.mcf2pdf.mcfelements.util.ImageUtil.java

public static BufferedImage readImage(File imageFile) throws IOException {
    int rotation = getImageRotation(imageFile);
    BufferedImage img = ImageIO.read(imageFile);

    if (rotation == 0) {
        return img;
    }//from   w w  w .j a v a  2 s. co m

    boolean swapXY = rotation != 180;

    BufferedImage rotated = new BufferedImage(swapXY ? img.getHeight() : img.getWidth(),
            swapXY ? img.getWidth() : img.getHeight(), BufferedImage.TYPE_INT_ARGB);
    Graphics2D g2d = rotated.createGraphics();
    g2d.translate((rotated.getWidth() - img.getWidth()) / 2, (rotated.getHeight() - img.getHeight()) / 2);
    g2d.rotate(Math.toRadians(rotation), img.getWidth() / 2, img.getHeight() / 2);

    g2d.drawImage(img, 0, 0, null);
    g2d.dispose();

    return rotated;
}

From source file:com.synnex.saas.platform.core.servlet.CaptchaServlet.java

public void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    try {// w  w w  .j a v a 2s .c  o m
        int width = 50;
        int height = 18;
        String captchaCode = RandomStringUtils.random(4, true, true);
        HttpSession session = request.getSession(true);
        session.setAttribute("captchaCode", captchaCode);

        response.setContentType("images/jpeg");
        response.setHeader("Pragma", "No-cache");
        response.setHeader("Cache-Control", "no-cache");
        response.setDateHeader("Expires", 0);

        ServletOutputStream out = response.getOutputStream();
        BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        Graphics g = image.getGraphics();
        g.setColor(getRandColor(200, 250));
        g.fillRect(0, 0, width, height);
        Font mFont = new Font("Times New Roman", Font.BOLD, 18);
        g.setFont(mFont);
        g.setColor(getRandColor(160, 200));
        Random random = new Random();
        for (int i = 0; i < 155; i++) {
            int x2 = random.nextInt(width);
            int y2 = random.nextInt(height);
            int x3 = random.nextInt(12);
            int y3 = random.nextInt(12);
            g.drawLine(x2, y2, x2 + x3, y2 + y3);
        }
        g.setColor(new Color(20 + random.nextInt(110), 20 + random.nextInt(110), 20 + random.nextInt(110)));
        g.drawString(captchaCode, 2, 16);
        g.dispose();
        ImageIO.write((BufferedImage) image, "JPEG", out);
        out.close();
    } catch (Exception e) {
        logger.error("Generate captcha failed.", e);
    }
}

From source file:Com.Operaciones.java

public static InputStream generateBarras(String text, int h, int w) throws Exception {

    Charset charset = Charset.forName("ISO-8859-1");
    CharsetEncoder encoder = charset.newEncoder();
    byte[] b = null;
    ByteBuffer bbuf = encoder.encode(CharBuffer.wrap(text));
    b = bbuf.array();//from  w  w w  .j ava  2 s.  c o  m
    String data = new String(b, "ISO-8859-1");
    // get a byte matrix for the data

    BitMatrix matrix = null;

    matrix = new Code128Writer().encode(data, BarcodeFormat.CODE_128, w, h, null);

    int height = matrix.getHeight();
    int width = matrix.getWidth();
    BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
    for (int x = 0; x < width; x++) {
        for (int y = 0; y < height; y++) {
            image.setRGB(x, y, matrix.get(x, y) ? BLACK : WHITE);
        }
    }

    byte[] imgByte = ChartUtilities.encodeAsPNG(image);

    InputStream myInputStream = new ByteArrayInputStream(imgByte);

    return myInputStream;

}

From source file:irille.pub.verify.RandomImageServlet.java

/**
 * ???,,?16,/*from  w  ww.j a  va 2  s  . c o m*/
 * @param num   ??
 * @param out   ?
 * @throws IOException
 */
protected static void render(String num, boolean gif, OutputStream out) throws IOException {
    if (num.getBytes().length > 4)
        throw new IllegalArgumentException("The length of param num cannot exceed 4.");
    int width = 50;
    int height = 18;
    BufferedImage bi = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
    Graphics2D g = (Graphics2D) bi.getGraphics();
    g.setColor(Color.WHITE);
    g.fillRect(0, 0, width, height);
    Font mFont = new Font("Tahoma", Font.BOLD | Font.ITALIC, 16);
    g.setFont(mFont);
    g.setColor(Color.BLACK);
    g.drawString(num, 2, 15);
    if (gif) {
        AnimatedGifEncoder e = new AnimatedGifEncoder();
        e.setTransparent(Color.WHITE);
        e.start(out);
        e.setDelay(0);
        e.addFrame(bi);
        e.finish();
    } else {
        ImageIO.write(bi, "png", out);
    }
}

From source file:Hypnosis.java

public Hypnosis(double x, double y, double r1, double r2, double a1, double a2, float linewidth, int delay,
        double deltaA, double deltaX, double deltaY) {
    this.x = x;// ww w .j av a 2 s.c  om
    this.y = y;
    this.r1 = r1;
    this.r2 = r2;
    this.a1 = a1;
    this.a2 = a2;
    this.linewidth = linewidth;
    this.deltaA = deltaA;
    this.deltaX = deltaX;
    this.deltaY = deltaY;

    // Set up a timer to call actionPerformed() every delay milliseconds
    timer = new Timer(delay, this);

    // Create a buffer for double-buffering
    buffer = new BufferedImage((int) (2 * r2 + linewidth), (int) (2 * r2 + linewidth),
            BufferedImage.TYPE_INT_RGB);

    // Create a Graphics object for the buffer, and set the linewidth
    // and request antialiasing when drawing with it
    osg = buffer.createGraphics();
    osg.setStroke(new BasicStroke(linewidth, BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND));
    osg.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
}

From source file:DrawingApplet.java

public void init() {
    // Find out how big the applet is and create an offscreen image
    // that size.
    int w = getWidth();
    int h = getHeight();
    image = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
    // Get a graphics context for drawing into the image
    g = image.createGraphics();/*from   ww w.  j  a  va  2s  . c o m*/
    // Start with a pure white background
    g.setPaint(Color.WHITE);
    g.fillRect(0, 0, w, h);
    // Turn on antialiasing
    g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);

    try {
        // sleep here to simulate a long init method
        Thread.sleep(4000);
    } catch (InterruptedException ie) {
        ie.printStackTrace();
    }
}

From source file:com.joliciel.jochre.graphics.VectorizerImpl.java

public BufferedImage drawArrayLists(JochreImage jochreImage) {
    long startTime = (new Date()).getTime();
    BufferedImage vectorizedImage = new BufferedImage(jochreImage.getWidth(), jochreImage.getHeight(),
            BufferedImage.TYPE_INT_ARGB);
    Graphics2D graphics2D = vectorizedImage.createGraphics();
    graphics2D.setStroke(new BasicStroke(1));
    graphics2D.setPaint(Color.BLACK);

    for (Paragraph paragraph : jochreImage.getParagraphs()) {
        for (RowOfShapes row : paragraph.getRows()) {
            for (GroupOfShapes group : row.getGroups()) {
                for (Shape shape : group.getShapes()) {
                    List<LineSegment> lines = this.vectorize(shape);

                    for (LineSegment line : lines)
                        graphics2D.drawLine(shape.getLeft() + line.getStartX(),
                                shape.getTop() + line.getStartY(), shape.getLeft() + line.getEndX(),
                                shape.getTop() + line.getEndY());
                }// ww w.  j  a  va  2 s.  c o m
            }
        }
    }

    if (LOG.isDebugEnabled()) {
        long endTime = (new Date()).getTime();
        long diff = endTime - startTime;
        LOG.debug("Time elapsed: " + ((double) diff / 1000));
    }
    return vectorizedImage;
}

From source file:net.sf.jasperreports.charts.util.ImageChartRendererFactory.java

@Override
public Renderable getRenderable(JasperReportsContext jasperReportsContext, JFreeChart chart,
        ChartHyperlinkProvider chartHyperlinkProvider, Rectangle2D rectangle) {
    int dpi = JRPropertiesUtil.getInstance(jasperReportsContext)
            .getIntegerProperty(Renderable.PROPERTY_IMAGE_DPI, 72);
    double scale = dpi / 72d;

    BufferedImage bi = new BufferedImage((int) (scale * (int) rectangle.getWidth()),
            (int) (scale * rectangle.getHeight()), BufferedImage.TYPE_INT_ARGB);

    List<JRPrintImageAreaHyperlink> areaHyperlinks = null;

    Graphics2D grx = bi.createGraphics();
    try {/*from   ww  w  .j  a  va2 s.  co  m*/
        grx.scale(scale, scale);

        if (chartHyperlinkProvider != null && chartHyperlinkProvider.hasHyperlinks()) {
            areaHyperlinks = ChartUtil.getImageAreaHyperlinks(chart, chartHyperlinkProvider, grx, rectangle);
        } else {
            chart.draw(grx, rectangle);
        }
    } finally {
        grx.dispose();
    }

    try {
        return new SimpleDataRenderer(
                JRImageLoader.getInstance(jasperReportsContext).loadBytesFromAwtImage(bi, ImageTypeEnum.PNG),
                areaHyperlinks);
    } catch (JRException e) {
        throw new JRRuntimeException(e);
    }
}

From source file:com.liusoft.dlog4j.servlet.DLOG_RandomImageServlet.java

/**
 * ???,,?16,/*  w  w w  .  j  av a 2s.  c om*/
 * @param num   ??
 * @param out   ?
 * @throws IOException
 */
protected static void render(String num, boolean gif, OutputStream out) throws IOException {
    if (num.getBytes().length > 4)
        throw new IllegalArgumentException("The length of param num cannot exceed 4.");
    int width = 40;
    int height = 15;
    BufferedImage bi = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
    Graphics2D g = (Graphics2D) bi.getGraphics();
    g.setColor(Color.WHITE);
    g.fillRect(0, 0, width, height);
    Font mFont = new Font("Tahoma", Font.PLAIN, 14);
    g.setFont(mFont);
    g.setColor(Color.BLACK);
    g.drawString(num, 2, 13);
    if (gif) {
        AnimatedGifEncoder e = new AnimatedGifEncoder();
        e.setTransparent(Color.WHITE);
        e.start(out);
        e.setDelay(0);
        e.addFrame(bi);
        e.finish();
    } else {
        ImageIO.write(bi, "png", out);
    }
}