List of usage examples for java.awt Graphics2D fillRect
public abstract void fillRect(int x, int y, int width, int height);
From source file:com.t3.image.ImageUtil.java
public static void clearImage(BufferedImage image) { if (image == null) { return;/*from w w w . java2 s .com*/ } Graphics2D g = null; try { g = (Graphics2D) image.getGraphics(); Composite oldComposite = g.getComposite(); g.setComposite(AlphaComposite.Clear); g.fillRect(0, 0, image.getWidth(), image.getHeight()); g.setComposite(oldComposite); } finally { if (g != null) { g.dispose(); } } }
From source file:org.mrgeo.resources.tms.TileMapServiceResource.java
protected static Response createEmptyTile(final ImageResponseWriter writer, final int width, final int height) { // return an empty image final int dataType; if (writer.getResponseMimeType().equals("image/jpeg")) { dataType = BufferedImage.TYPE_3BYTE_BGR; } else {//www .java2 s . co m // dataType = BufferedImage.TYPE_INT_ARGB; dataType = BufferedImage.TYPE_4BYTE_ABGR; } final BufferedImage bufImg = new BufferedImage(width, height, dataType); final Graphics2D g = bufImg.createGraphics(); g.setColor(new Color(0, 0, 0, 0)); g.fillRect(0, 0, width, height); g.dispose(); return writer.write(bufImg.getData()).build(); }
From source file:org.apache.ofbiz.common.CommonEvents.java
public static String getCaptcha(HttpServletRequest request, HttpServletResponse response) { try {/*ww w . j av a 2 s .co m*/ Delegator delegator = (Delegator) request.getAttribute("delegator"); final String captchaSizeConfigName = StringUtils.defaultIfEmpty(request.getParameter("captchaSize"), "default"); final String captchaSizeConfig = EntityUtilProperties.getPropertyValue("captcha", "captcha." + captchaSizeConfigName, delegator); final String[] captchaSizeConfigs = captchaSizeConfig.split("\\|"); final String captchaCodeId = StringUtils.defaultIfEmpty(request.getParameter("captchaCodeId"), ""); // this is used to uniquely identify in the user session the attribute where the captcha code for the last captcha for the form is stored final int fontSize = Integer.parseInt(captchaSizeConfigs[0]); final int height = Integer.parseInt(captchaSizeConfigs[1]); final int width = Integer.parseInt(captchaSizeConfigs[2]); final int charsToPrint = UtilProperties.getPropertyAsInteger("captcha", "captcha.code_length", 6); final char[] availableChars = EntityUtilProperties .getPropertyValue("captcha", "captcha.characters", delegator).toCharArray(); //It is possible to pass the font size, image width and height with the request as well Color backgroundColor = Color.gray; Color borderColor = Color.DARK_GRAY; Color textColor = Color.ORANGE; Color circleColor = new Color(160, 160, 160); Font textFont = new Font("Arial", Font.PLAIN, fontSize); int circlesToDraw = 6; float horizMargin = 20.0f; double rotationRange = 0.7; // in radians BufferedImage bufferedImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB); Graphics2D g = (Graphics2D) bufferedImage.getGraphics(); g.setColor(backgroundColor); g.fillRect(0, 0, width, height); //Generating some circles for background noise g.setColor(circleColor); for (int i = 0; i < circlesToDraw; i++) { int circleRadius = (int) (Math.random() * height / 2.0); int circleX = (int) (Math.random() * width - circleRadius); int circleY = (int) (Math.random() * height - circleRadius); g.drawOval(circleX, circleY, circleRadius * 2, circleRadius * 2); } g.setColor(textColor); g.setFont(textFont); FontMetrics fontMetrics = g.getFontMetrics(); int maxAdvance = fontMetrics.getMaxAdvance(); int fontHeight = fontMetrics.getHeight(); String captchaCode = RandomStringUtils.random(6, availableChars); float spaceForLetters = -horizMargin * 2 + width; float spacePerChar = spaceForLetters / (charsToPrint - 1.0f); for (int i = 0; i < captchaCode.length(); i++) { // this is a separate canvas used for the character so that // we can rotate it independently int charWidth = fontMetrics.charWidth(captchaCode.charAt(i)); int charDim = Math.max(maxAdvance, fontHeight); int halfCharDim = (charDim / 2); BufferedImage charImage = new BufferedImage(charDim, charDim, BufferedImage.TYPE_INT_ARGB); Graphics2D charGraphics = charImage.createGraphics(); charGraphics.translate(halfCharDim, halfCharDim); double angle = (Math.random() - 0.5) * rotationRange; charGraphics.transform(AffineTransform.getRotateInstance(angle)); charGraphics.translate(-halfCharDim, -halfCharDim); charGraphics.setColor(textColor); charGraphics.setFont(textFont); int charX = (int) (0.5 * charDim - 0.5 * charWidth); charGraphics.drawString("" + captchaCode.charAt(i), charX, ((charDim - fontMetrics.getAscent()) / 2 + fontMetrics.getAscent())); float x = horizMargin + spacePerChar * (i) - charDim / 2.0f; int y = ((height - charDim) / 2); g.drawImage(charImage, (int) x, y, charDim, charDim, null, null); charGraphics.dispose(); } // Drawing the image border g.setColor(borderColor); g.drawRect(0, 0, width - 1, height - 1); g.dispose(); response.setContentType("image/jpeg"); ImageIO.write(bufferedImage, "jpg", response.getOutputStream()); HttpSession session = request.getSession(); Map<String, String> captchaCodeMap = UtilGenerics.checkMap(session.getAttribute("_CAPTCHA_CODE_")); if (captchaCodeMap == null) { captchaCodeMap = new HashMap<String, String>(); session.setAttribute("_CAPTCHA_CODE_", captchaCodeMap); } captchaCodeMap.put(captchaCodeId, captchaCode); } catch (Exception ioe) { Debug.logError(ioe.getMessage(), module); } return "success"; }
From source file:org.ofbiz.common.CommonEvents.java
public static String getCaptcha(HttpServletRequest request, HttpServletResponse response) { try {/*from www.j a v a 2 s. c om*/ Delegator delegator = (Delegator) request.getAttribute("delegator"); final String captchaSizeConfigName = StringUtils.defaultIfEmpty(request.getParameter("captchaSize"), "default"); final String captchaSizeConfig = EntityUtilProperties.getPropertyValue("captcha.properties", "captcha." + captchaSizeConfigName, delegator); final String[] captchaSizeConfigs = captchaSizeConfig.split("\\|"); final String captchaCodeId = StringUtils.defaultIfEmpty(request.getParameter("captchaCodeId"), ""); // this is used to uniquely identify in the user session the attribute where the captcha code for the last captcha for the form is stored final int fontSize = Integer.parseInt(captchaSizeConfigs[0]); final int height = Integer.parseInt(captchaSizeConfigs[1]); final int width = Integer.parseInt(captchaSizeConfigs[2]); final int charsToPrint = UtilProperties.getPropertyAsInteger("captcha.properties", "captcha.code_length", 6); final char[] availableChars = EntityUtilProperties .getPropertyValue("captcha.properties", "captcha.characters", delegator).toCharArray(); //It is possible to pass the font size, image width and height with the request as well Color backgroundColor = Color.gray; Color borderColor = Color.DARK_GRAY; Color textColor = Color.ORANGE; Color circleColor = new Color(160, 160, 160); Font textFont = new Font("Arial", Font.PLAIN, fontSize); int circlesToDraw = 6; float horizMargin = 20.0f; double rotationRange = 0.7; // in radians BufferedImage bufferedImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB); Graphics2D g = (Graphics2D) bufferedImage.getGraphics(); g.setColor(backgroundColor); g.fillRect(0, 0, width, height); //Generating some circles for background noise g.setColor(circleColor); for (int i = 0; i < circlesToDraw; i++) { int circleRadius = (int) (Math.random() * height / 2.0); int circleX = (int) (Math.random() * width - circleRadius); int circleY = (int) (Math.random() * height - circleRadius); g.drawOval(circleX, circleY, circleRadius * 2, circleRadius * 2); } g.setColor(textColor); g.setFont(textFont); FontMetrics fontMetrics = g.getFontMetrics(); int maxAdvance = fontMetrics.getMaxAdvance(); int fontHeight = fontMetrics.getHeight(); String captchaCode = RandomStringUtils.random(6, availableChars); float spaceForLetters = -horizMargin * 2 + width; float spacePerChar = spaceForLetters / (charsToPrint - 1.0f); for (int i = 0; i < captchaCode.length(); i++) { // this is a separate canvas used for the character so that // we can rotate it independently int charWidth = fontMetrics.charWidth(captchaCode.charAt(i)); int charDim = Math.max(maxAdvance, fontHeight); int halfCharDim = (charDim / 2); BufferedImage charImage = new BufferedImage(charDim, charDim, BufferedImage.TYPE_INT_ARGB); Graphics2D charGraphics = charImage.createGraphics(); charGraphics.translate(halfCharDim, halfCharDim); double angle = (Math.random() - 0.5) * rotationRange; charGraphics.transform(AffineTransform.getRotateInstance(angle)); charGraphics.translate(-halfCharDim, -halfCharDim); charGraphics.setColor(textColor); charGraphics.setFont(textFont); int charX = (int) (0.5 * charDim - 0.5 * charWidth); charGraphics.drawString("" + captchaCode.charAt(i), charX, ((charDim - fontMetrics.getAscent()) / 2 + fontMetrics.getAscent())); float x = horizMargin + spacePerChar * (i) - charDim / 2.0f; int y = ((height - charDim) / 2); g.drawImage(charImage, (int) x, y, charDim, charDim, null, null); charGraphics.dispose(); } // Drawing the image border g.setColor(borderColor); g.drawRect(0, 0, width - 1, height - 1); g.dispose(); response.setContentType("image/jpeg"); ImageIO.write(bufferedImage, "jpg", response.getOutputStream()); HttpSession session = request.getSession(); Map<String, String> captchaCodeMap = UtilGenerics.checkMap(session.getAttribute("_CAPTCHA_CODE_")); if (captchaCodeMap == null) { captchaCodeMap = new HashMap<String, String>(); session.setAttribute("_CAPTCHA_CODE_", captchaCodeMap); } captchaCodeMap.put(captchaCodeId, captchaCode); } catch (Exception ioe) { Debug.logError(ioe.getMessage(), module); } return "success"; }
From source file:com.aimluck.eip.fileupload.util.FileuploadUtils.java
/** * ?????????// w w w .j a va 2s. c om * * @param imgfile * @param dim * @return */ public static BufferedImage shrinkImage(BufferedImage imgfile, int width, int height) { int iwidth = imgfile.getWidth(); int iheight = imgfile.getHeight(); double ratio = Math.min((double) width / (double) iwidth, (double) height / (double) iheight); int shrinkedWidth = (int) (iwidth * ratio); int shrinkedHeight = (int) (iheight * ratio); // ?? Image targetImage = imgfile.getScaledInstance(shrinkedWidth, shrinkedHeight, Image.SCALE_AREA_AVERAGING); BufferedImage tmpImage = new BufferedImage(targetImage.getWidth(null), targetImage.getHeight(null), BufferedImage.TYPE_3BYTE_BGR); Graphics2D g = tmpImage.createGraphics(); g.setColor(Color.WHITE); g.fillRect(0, 0, shrinkedWidth, shrinkedHeight); g.drawImage(targetImage, 0, 0, null); return tmpImage; }
From source file:net.pms.util.UMSUtils.java
@SuppressWarnings("deprecation") public static InputStream scaleThumb(InputStream in, RendererConfiguration r) throws IOException { if (in == null) { return in; }// w w w . j a v a 2 s.c om String ts = r.getThumbSize(); if (StringUtils.isEmpty(ts) && StringUtils.isEmpty(r.getThumbBG())) { // no need to convert here return in; } int w; int h; Color col = null; BufferedImage img; try { img = ImageIO.read(in); } catch (Exception e) { // catch whatever is thrown at us // we can at least log it LOGGER.debug("couldn't read thumb to manipulate it " + e); img = null; // to make sure } if (img == null) { return in; } w = img.getWidth(); h = img.getHeight(); if (StringUtils.isNotEmpty(ts)) { // size limit thumbnail w = getHW(ts.split("x"), 0); h = getHW(ts.split("x"), 1); if (w == 0 || h == 0) { LOGGER.debug("bad thumb size {} skip scaling", ts); w = h = 0; // just to make sure } } if (StringUtils.isNotEmpty(r.getThumbBG())) { try { Field field = Color.class.getField(r.getThumbBG()); col = (Color) field.get(null); } catch (Exception e) { LOGGER.debug("bad color name " + r.getThumbBG()); } } if (w == 0 && h == 0 && col == null) { return in; } ByteArrayOutputStream out = new ByteArrayOutputStream(); BufferedImage img1 = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB); Graphics2D g = img1.createGraphics(); if (col != null) { g.setColor(col); } g.fillRect(0, 0, w, h); g.drawImage(img, 0, 0, w, h, null); ImageIO.write(img1, "jpeg", out); out.flush(); return new ByteArrayInputStream(out.toByteArray()); }
From source file:weka.core.ChartUtils.java
/** * Render a combined histogram and pie chart from summary data * //w ww .j av a2s. c om * @param width the width of the resulting image * @param height the height of the resulting image * @param values the values for the chart * @param freqs the corresponding frequencies * @param additionalArgs optional arguments to the renderer (may be null) * @return a buffered image * @throws Exception if a problem occurs */ public static BufferedImage renderCombinedPieAndHistogramFromSummaryData(int width, int height, List<String> values, List<Double> freqs, List<String> additionalArgs) throws Exception { String plotTitle = "Combined Chart"; String userTitle = getOption(additionalArgs, "-title"); plotTitle = (userTitle != null) ? userTitle : plotTitle; List<String> opts = new ArrayList<String>(); opts.add("-title=distribution"); BufferedImage pie = renderPieChartFromSummaryData(width / 2, height, values, freqs, false, true, opts); opts.clear(); opts.add("-title=histogram"); BufferedImage hist = renderHistogramFromSummaryData(width / 2, height, values, freqs, opts); BufferedImage img = new BufferedImage(width, height + 20, BufferedImage.TYPE_INT_ARGB); Graphics2D g2d = img.createGraphics(); g2d.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_GASP); g2d.setFont(new Font("SansSerif", Font.BOLD, 12)); g2d.setColor(Color.lightGray); g2d.fillRect(0, 0, width, height + 20); g2d.setColor(Color.black); FontMetrics fm = g2d.getFontMetrics(); int fh = fm.getHeight(); int sw = fm.stringWidth(plotTitle); g2d.drawImage(pie, 0, 20, null); g2d.drawImage(hist, width / 2 + 1, 20, null); g2d.drawString(plotTitle, width / 2 - sw / 2, fh + 2); g2d.dispose(); return img; }
From source file:weka.core.ChartUtils.java
/** * Render a combined histogram and box plot chart from summary data * /*w w w . j a v a2s . c o m*/ * @param width the width of the resulting image * @param height the height of the resulting image * @param bins the values for the chart * @param freqs the corresponding frequencies * @param summary the summary stats for the box plot * @param outliers an optional list of outliers for the box plot * @param additionalArgs optional arguments to the renderer (may be null) * @return a buffered image * @throws Exception if a problem occurs */ public static BufferedImage renderCombinedBoxPlotAndHistogramFromSummaryData(int width, int height, List<String> bins, List<Double> freqs, List<Double> summary, List<Double> outliers, List<String> additionalArgs) throws Exception { String plotTitle = "Combined Chart"; String userTitle = getOption(additionalArgs, "-title"); plotTitle = (userTitle != null) ? userTitle : plotTitle; List<String> opts = new ArrayList<String>(); opts.add("-title=histogram"); BufferedImage hist = renderHistogramFromSummaryData(width / 2, height, bins, freqs, opts); opts.clear(); opts.add("-title=box plot"); BufferedImage box = null; try { box = renderBoxPlotFromSummaryData(width / 2, height, summary, outliers, opts); } catch (Exception ex) { // if we can't generate the box plot (i.e. probably because // data is 100% missing) then just return the histogram } if (box == null) { width /= 2; } BufferedImage img = new BufferedImage(width, height + 20, BufferedImage.TYPE_INT_ARGB); Graphics2D g2d = img.createGraphics(); g2d.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_GASP); g2d.setFont(new Font("SansSerif", Font.BOLD, 12)); g2d.setColor(Color.lightGray); g2d.fillRect(0, 0, width, height + 20); g2d.setColor(Color.black); FontMetrics fm = g2d.getFontMetrics(); int fh = fm.getHeight(); int sw = fm.stringWidth(plotTitle); if (box != null) { g2d.drawImage(box, 0, 20, null); g2d.drawImage(hist, width / 2 + 1, 20, null); } else { g2d.drawImage(hist, 0, 20, null); } g2d.drawString(plotTitle, width / 2 - sw / 2, fh + 2); g2d.dispose(); return img; }
From source file:main.java.whiteSocket.Bloop.java
public static BufferedImage createWhiteImage() { BufferedImage testOut = new BufferedImage(Bloop.blooprint.getWidth(), Bloop.blooprint.getHeight(), BufferedImage.TYPE_INT_RGB); Graphics2D graphics = testOut.createGraphics(); graphics.setPaint(Color.white); graphics.fillRect(0, 0, testOut.getWidth(), testOut.getHeight()); return testOut; }
From source file:com.sun.socialsite.util.ImageUtil.java
public static BufferedImage getScaledImage(BufferedImage origImage, Integer desiredWidth, Integer desiredHeight) throws IOException { if (origImage == null) { return null; }/*from w w w . ja v a 2s . c o m*/ if (desiredWidth == null) { desiredWidth = origImage.getWidth(); } if (desiredHeight == null) { desiredHeight = origImage.getHeight(); } int origWidth = origImage.getWidth(); int origHeight = origImage.getHeight(); double ratio = Math.min((((double) desiredWidth) / origWidth), (((double) desiredHeight) / origHeight)); int extraWidth = desiredWidth - ((int) (origWidth * ratio)); int extraHeight = desiredHeight - ((int) (origHeight * ratio)); int tmpWidth = (desiredWidth - extraWidth); int tmpHeight = (desiredHeight - extraHeight); BufferedImage tmpImage = getScaledInstance(origImage, tmpWidth, tmpHeight, RenderingHints.VALUE_INTERPOLATION_BICUBIC, true); log.debug(String.format("tmpImage[width=%d height=%d", tmpImage.getWidth(), tmpImage.getHeight())); if ((tmpImage.getWidth() == desiredWidth) && (tmpImage.getHeight() == desiredHeight)) { return tmpImage; } else { BufferedImage scaledImage = new BufferedImage(desiredWidth, desiredHeight, BufferedImage.TYPE_INT_ARGB); Graphics2D g2d = scaledImage.createGraphics(); g2d.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BICUBIC); // We recalculate these in case scaling didn't quite hit its targets extraWidth = desiredWidth - tmpImage.getWidth(); extraHeight = desiredHeight - tmpImage.getHeight(); int dx1 = extraWidth / 2; int dy1 = extraHeight / 2; int dx2 = desiredWidth - dx1; int dy2 = desiredWidth - dy1; // transparent background g2d.setColor(new Color(0, 0, 0, 0)); g2d.fillRect(0, 0, desiredWidth, desiredHeight); g2d.drawImage(tmpImage, dx1, dy1, dx2, dy2, null); return scaledImage; } }