List of usage examples for java.awt Graphics2D setBackground
public abstract void setBackground(Color color);
From source file:net.groupbuy.util.ImageUtils.java
/** * // w w w .jav a 2 s .co m * * @param srcFile * ? * @param destFile * * @param destWidth * * @param destHeight * */ public static void zoom(File srcFile, File destFile, int destWidth, int destHeight) { Assert.notNull(srcFile); Assert.notNull(destFile); Assert.state(destWidth > 0); Assert.state(destHeight > 0); if (type == Type.jdk) { Graphics2D graphics2D = null; ImageOutputStream imageOutputStream = null; ImageWriter imageWriter = null; try { BufferedImage srcBufferedImage = ImageIO.read(srcFile); int srcWidth = srcBufferedImage.getWidth(); int srcHeight = srcBufferedImage.getHeight(); int width = destWidth; int height = destHeight; if (srcHeight >= srcWidth) { width = (int) Math.round(((destHeight * 1.0 / srcHeight) * srcWidth)); } else { height = (int) Math.round(((destWidth * 1.0 / srcWidth) * srcHeight)); } BufferedImage destBufferedImage = new BufferedImage(destWidth, destHeight, BufferedImage.TYPE_INT_RGB); graphics2D = destBufferedImage.createGraphics(); graphics2D.setBackground(BACKGROUND_COLOR); graphics2D.clearRect(0, 0, destWidth, destHeight); graphics2D.drawImage(srcBufferedImage.getScaledInstance(width, height, Image.SCALE_SMOOTH), (destWidth / 2) - (width / 2), (destHeight / 2) - (height / 2), null); imageOutputStream = ImageIO.createImageOutputStream(destFile); imageWriter = ImageIO.getImageWritersByFormatName(FilenameUtils.getExtension(destFile.getName())) .next(); imageWriter.setOutput(imageOutputStream); ImageWriteParam imageWriteParam = imageWriter.getDefaultWriteParam(); imageWriteParam.setCompressionMode(ImageWriteParam.MODE_EXPLICIT); imageWriteParam.setCompressionQuality((float) (DEST_QUALITY / 100.0)); imageWriter.write(null, new IIOImage(destBufferedImage, null, null), imageWriteParam); imageOutputStream.flush(); } catch (IOException e) { e.printStackTrace(); } finally { if (graphics2D != null) { graphics2D.dispose(); } if (imageWriter != null) { imageWriter.dispose(); } if (imageOutputStream != null) { try { imageOutputStream.close(); } catch (IOException e) { } } } } else { IMOperation operation = new IMOperation(); operation.thumbnail(destWidth, destHeight); operation.gravity("center"); operation.background(toHexEncoding(BACKGROUND_COLOR)); operation.extent(destWidth, destHeight); operation.quality((double) DEST_QUALITY); operation.addImage(srcFile.getPath()); operation.addImage(destFile.getPath()); if (type == Type.graphicsMagick) { ConvertCmd convertCmd = new ConvertCmd(true); if (graphicsMagickPath != null) { convertCmd.setSearchPath(graphicsMagickPath); } try { convertCmd.run(operation); } catch (IOException e) { e.printStackTrace(); } catch (InterruptedException e) { e.printStackTrace(); } catch (IM4JavaException e) { e.printStackTrace(); } } else { ConvertCmd convertCmd = new ConvertCmd(false); if (imageMagickPath != null) { convertCmd.setSearchPath(imageMagickPath); } try { convertCmd.run(operation); } catch (IOException e) { e.printStackTrace(); } catch (InterruptedException e) { e.printStackTrace(); } catch (IM4JavaException e) { e.printStackTrace(); } } } }
From source file:com.el.ecom.utils.ImageUtils.java
/** * //from w ww .j a v a 2 s .c o m * * @param srcFile ? * @param destFile * @param destWidth * @param destHeight */ public static void zoom(File srcFile, File destFile, int destWidth, int destHeight) { Assert.notNull(srcFile); Assert.state(srcFile.exists()); Assert.state(srcFile.isFile()); Assert.notNull(destFile); Assert.state(destWidth > 0); Assert.state(destHeight > 0); if (type == Type.jdk) { Graphics2D graphics2D = null; ImageOutputStream imageOutputStream = null; ImageWriter imageWriter = null; try { BufferedImage srcBufferedImage = ImageIO.read(srcFile); int srcWidth = srcBufferedImage.getWidth(); int srcHeight = srcBufferedImage.getHeight(); int width = destWidth; int height = destHeight; if (srcHeight >= srcWidth) { width = (int) Math.round(((destHeight * 1.0 / srcHeight) * srcWidth)); } else { height = (int) Math.round(((destWidth * 1.0 / srcWidth) * srcHeight)); } BufferedImage destBufferedImage = new BufferedImage(destWidth, destHeight, BufferedImage.TYPE_INT_RGB); graphics2D = destBufferedImage.createGraphics(); graphics2D.setBackground(BACKGROUND_COLOR); graphics2D.clearRect(0, 0, destWidth, destHeight); graphics2D.drawImage(srcBufferedImage.getScaledInstance(width, height, Image.SCALE_SMOOTH), (destWidth / 2) - (width / 2), (destHeight / 2) - (height / 2), null); imageOutputStream = ImageIO.createImageOutputStream(destFile); imageWriter = ImageIO.getImageWritersByFormatName(FilenameUtils.getExtension(destFile.getName())) .next(); imageWriter.setOutput(imageOutputStream); ImageWriteParam imageWriteParam = imageWriter.getDefaultWriteParam(); imageWriteParam.setCompressionMode(ImageWriteParam.MODE_EXPLICIT); imageWriteParam.setCompressionQuality((float) (DEST_QUALITY / 100.0)); imageWriter.write(null, new IIOImage(destBufferedImage, null, null), imageWriteParam); imageOutputStream.flush(); } catch (IOException e) { throw new RuntimeException(e.getMessage(), e); } finally { if (graphics2D != null) { graphics2D.dispose(); } if (imageWriter != null) { imageWriter.dispose(); } try { if (imageOutputStream != null) { imageOutputStream.close(); } } catch (IOException e) { } } } else { IMOperation operation = new IMOperation(); operation.thumbnail(destWidth, destHeight); operation.gravity("center"); operation.background(toHexEncoding(BACKGROUND_COLOR)); operation.extent(destWidth, destHeight); operation.quality((double) DEST_QUALITY); try { operation.addImage(srcFile.getCanonicalPath()); operation.addImage(destFile.getCanonicalPath()); } catch (IOException e) { throw new RuntimeException(e.getMessage(), e); } if (type == Type.graphicsMagick) { ConvertCmd convertCmd = new ConvertCmd(true); if (graphicsMagickPath != null) { convertCmd.setSearchPath(graphicsMagickPath); } try { convertCmd.run(operation); } catch (IOException e) { throw new RuntimeException(e.getMessage(), e); } catch (InterruptedException e) { throw new RuntimeException(e.getMessage(), e); } catch (IM4JavaException e) { throw new RuntimeException(e.getMessage(), e); } } else { ConvertCmd convertCmd = new ConvertCmd(false); if (imageMagickPath != null) { convertCmd.setSearchPath(imageMagickPath); } try { convertCmd.run(operation); } catch (IOException e) { throw new RuntimeException(e.getMessage(), e); } catch (InterruptedException e) { throw new RuntimeException(e.getMessage(), e); } catch (IM4JavaException e) { throw new RuntimeException(e.getMessage(), e); } } } }
From source file:org.jrecruiter.service.impl.DataServiceImpl.java
/** {@inheritDoc} */ @Transactional(readOnly = true, propagation = Propagation.SUPPORTS) public Image getGoogleMapImage(final BigDecimal latitude, final BigDecimal longitude, final Integer zoomLevel) { if (longitude == null) { throw new IllegalArgumentException("Longitude cannot be null."); }/*from w ww. jav a 2 s .com*/ if (latitude == null) { throw new IllegalArgumentException("Latitude cannot be null."); } if (zoomLevel == null) { throw new IllegalArgumentException("ZoomLevel cannot be null."); } final URI url = GoogleMapsUtils.buildGoogleMapsStaticUrl(latitude, longitude, zoomLevel); BufferedImage img; try { URLConnection conn = url.toURL().openConnection(); img = ImageIO.read(conn.getInputStream()); } catch (UnknownHostException e) { LOGGER.error("Google static MAPS web service is not reachable (UnknownHostException).", e); img = new BufferedImage(GoogleMapsUtils.defaultWidth, 100, BufferedImage.TYPE_INT_RGB); final Graphics2D graphics = img.createGraphics(); final Map<Object, Object> renderingHints = CollectionUtils.getHashMap(); renderingHints.put(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON); graphics.addRenderingHints(renderingHints); graphics.setBackground(Color.WHITE); graphics.setColor(Color.GRAY); graphics.clearRect(0, 0, GoogleMapsUtils.defaultWidth, 100); graphics.drawString("Not Available", 30, 30); } catch (IOException e) { throw new IllegalStateException(e); } return img; }
From source file:edworld.pdfreader4humans.PDFReader.java
public BufferedImage createPageImage(int pageNumber, int scaling, Color inkColor, Color backgroundColor, boolean showStructure) throws IOException { Map<String, Font> fonts = new HashMap<String, Font>(); PDRectangle cropBox = getPageCropBox(pageNumber); BufferedImage image = new BufferedImage(Math.round(cropBox.getWidth() * scaling), Math.round(cropBox.getHeight() * scaling), BufferedImage.TYPE_INT_ARGB); Graphics2D graphics = image.createGraphics(); graphics.setBackground(backgroundColor); graphics.clearRect(0, 0, image.getWidth(), image.getHeight()); graphics.setColor(backgroundColor);/*from w w w .j a va 2s .c om*/ graphics.fillRect(0, 0, image.getWidth(), image.getHeight()); graphics.setColor(inkColor); graphics.scale(scaling, scaling); for (Component component : getFirstLevelComponents(pageNumber)) draw(component, graphics, inkColor, backgroundColor, showStructure, fonts); graphics.dispose(); return image; }
From source file:io.github.dsheirer.spectrum.SpectrumPanel.java
@Override public void paintComponent(Graphics g) { super.paintComponent(g); Graphics2D graphics = (Graphics2D) g; graphics.setBackground(mColorSpectrumBackground); graphics.setRenderingHints(RENDERING_HINTS); drawSpectrum(graphics);//from w w w. ja v a2 s. c o m }
From source file:edu.umn.cs.spatialHadoop.operations.GeometricPlot.java
private static <S extends Shape> void plotLocal(Path inFile, Path outFile, OperationsParams params) throws IOException { int width = params.getInt("width", 1000); int height = params.getInt("height", 1000); Color strokeColor = params.getColor("color", Color.BLACK); int color = strokeColor.getRGB(); String hdfDataset = (String) params.get("dataset"); Shape shape = hdfDataset != null ? new NASARectangle() : (Shape) params.getShape("shape", null); Shape plotRange = params.getShape("rect", null); boolean keepAspectRatio = params.is("keep-ratio", true); String valueRangeStr = (String) params.get("valuerange"); MinMax valueRange;// w w w.j a v a 2 s. c o m if (valueRangeStr == null) { valueRange = null; } else { String[] parts = valueRangeStr.split(","); valueRange = new MinMax(Integer.parseInt(parts[0]), Integer.parseInt(parts[1])); } InputSplit[] splits; FileSystem inFs = inFile.getFileSystem(params); FileStatus inFStatus = inFs.getFileStatus(inFile); if (inFStatus != null && !inFStatus.isDir()) { // One file, retrieve it immediately. // This is useful if the input is a hidden file which is automatically // skipped by FileInputFormat. We need to plot a hidden file for the case // of plotting partition boundaries of a spatial index splits = new InputSplit[] { new FileSplit(inFile, 0, inFStatus.getLen(), new String[0]) }; } else { JobConf job = new JobConf(params); ShapeInputFormat<Shape> inputFormat = new ShapeInputFormat<Shape>(); ShapeInputFormat.addInputPath(job, inFile); splits = inputFormat.getSplits(job, 1); } boolean vflip = params.is("vflip"); Rectangle fileMbr; if (plotRange != null) { fileMbr = plotRange.getMBR(); } else if (hdfDataset != null) { // Plotting a NASA file fileMbr = new Rectangle(-180, -90, 180, 90); } else { fileMbr = FileMBR.fileMBR(inFile, params); } if (keepAspectRatio) { // Adjust width and height to maintain aspect ratio if (fileMbr.getWidth() / fileMbr.getHeight() > (double) width / height) { // Fix width and change height height = (int) (fileMbr.getHeight() * width / fileMbr.getWidth()); } else { width = (int) (fileMbr.getWidth() * height / fileMbr.getHeight()); } } boolean adaptiveSample = shape instanceof Point && params.getBoolean("sample", false); float adaptiveSampleRatio = 0.0f; if (adaptiveSample) { // Calculate the sample ratio long recordCount = FileMBR.fileMBR(inFile, params).recordCount; adaptiveSampleRatio = params.getFloat(AdaptiveSampleFactor, 1.0f) * width * height / recordCount; } boolean gradualFade = !(shape instanceof Point) && params.getBoolean("fade", false); if (hdfDataset != null) { // Collects some stats about the HDF file if (valueRange == null) valueRange = Aggregate.aggregate(new Path[] { inFile }, params); NASAPoint.minValue = valueRange.minValue; NASAPoint.maxValue = valueRange.maxValue; NASAPoint.setColor1(params.getColor("color1", Color.BLUE)); NASAPoint.setColor2(params.getColor("color2", Color.RED)); NASAPoint.gradientType = params.getGradientType("gradient", NASAPoint.GradientType.GT_HUE); } double scale2 = (double) width * height / (fileMbr.getWidth() * fileMbr.getHeight()); double scale = Math.sqrt(scale2); // Create an image BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB); Graphics2D graphics = image.createGraphics(); Color bg_color = params.getColor("bgcolor", new Color(0, 0, 0, 0)); graphics.setBackground(bg_color); graphics.clearRect(0, 0, width, height); graphics.setColor(strokeColor); for (InputSplit split : splits) { if (hdfDataset != null) { // Read points from the HDF file RecordReader<NASADataset, NASAShape> reader = new HDFRecordReader(params, (FileSplit) split, hdfDataset, true); NASADataset dataset = reader.createKey(); while (reader.next(dataset, (NASAShape) shape)) { // Skip with a fixed ratio if adaptive sample is set if (adaptiveSample && Math.random() > adaptiveSampleRatio) continue; if (plotRange == null || shape.isIntersected(shape)) { shape.draw(graphics, fileMbr, width, height, 0.0); } } reader.close(); } else { RecordReader<Rectangle, Shape> reader = new ShapeRecordReader<Shape>(params, (FileSplit) split); Rectangle cell = reader.createKey(); while (reader.next(cell, shape)) { // Skip with a fixed ratio if adaptive sample is set if (adaptiveSample && Math.random() > adaptiveSampleRatio) continue; Rectangle shapeMBR = shape.getMBR(); if (shapeMBR != null) { if (plotRange == null || shapeMBR.isIntersected(plotRange)) { if (gradualFade) { double sizeInPixels = (shapeMBR.getWidth() + shapeMBR.getHeight()) * scale; if (sizeInPixels < 1.0 && Math.round(sizeInPixels * 255) < 1.0) { // This shape can be safely skipped as it is too small to be plotted continue; } else { int alpha = (int) Math.round(sizeInPixels * 255); graphics.setColor(new Color((alpha << 24) | color, true)); } } shape.draw(graphics, fileMbr, width, height, scale2); } } } reader.close(); } } // Write image to output graphics.dispose(); if (vflip) { AffineTransform tx = AffineTransform.getScaleInstance(1, -1); tx.translate(0, -image.getHeight()); AffineTransformOp op = new AffineTransformOp(tx, AffineTransformOp.TYPE_NEAREST_NEIGHBOR); image = op.filter(image, null); } FileSystem outFs = outFile.getFileSystem(params); OutputStream out = outFs.create(outFile, true); ImageIO.write(image, "png", out); out.close(); }
From source file:ClipImage.java
public Graphics2D createDemoGraphics2D(Graphics g) { Graphics2D g2 = null; if (offImg == null || offImg.getWidth() != w || offImg.getHeight() != h) { offImg = (BufferedImage) createImage(w, h); newBufferedImage = true;/* w w w .j a v a 2 s . co m*/ } if (offImg != null) { g2 = offImg.createGraphics(); g2.setBackground(getBackground()); } // .. set attributes .. g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); g2.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY); // .. clear canvas .. g2.clearRect(0, 0, w, h); return g2; }
From source file:ClipImage.java
public Graphics2D createDemoGraphics2D(Graphics g) { Graphics2D g2 = null; if (offImg == null || offImg.getWidth() != w || offImg.getHeight() != h) { offImg = (BufferedImage) createImage(w, h); newBufferedImage = true;//w ww. ja va2 s . c om } if (offImg != null) { g2 = offImg.createGraphics(); g2.setBackground(getBackground()); } // .. set attributes .. g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); g2.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY); // .. clear canvas .. g2.clearRect(0, 0, w, h); return g2; }
From source file:com.esri.ArcGISController.java
@RequestMapping(value = "/rest/services/InfoUSA/MapServer/export", method = { RequestMethod.GET, RequestMethod.POST })//ww w. j av a2 s . co m public void doExport(@RequestParam("bbox") final String bbox, @RequestParam(value = "size", required = false) final String size, @RequestParam(value = "layerDefs", required = false) final String layerDefs, @RequestParam(value = "transparent", required = false) final String transparent, final HttpServletResponse response) throws IOException { double xmin = -1.0, ymin = -1.0, xmax = 1.0, ymax = 1.0; if (bbox != null && bbox.length() > 0) { final String[] tokens = m_patternComma.split(bbox); if (tokens.length == 4) { xmin = Double.parseDouble(tokens[0]); ymin = Double.parseDouble(tokens[1]); xmax = Double.parseDouble(tokens[2]); ymax = Double.parseDouble(tokens[3]); } else { response.sendError(HttpServletResponse.SC_BAD_REQUEST, "bbox is not in the form xmin,ymin,xmax,ymax"); return; } } else { response.sendError(HttpServletResponse.SC_BAD_REQUEST, "bbox is null or empty"); return; } final double xdel = xmax - xmin; final double ydel = ymax - ymin; int imageWidth = 400; int imageHeight = 400; if (size != null && size.length() > 0) { final String[] tokens = m_patternComma.split(size); if (tokens.length == 2) { imageWidth = Integer.parseInt(tokens[0], 10); imageHeight = Integer.parseInt(tokens[1], 10); } else { response.sendError(HttpServletResponse.SC_BAD_REQUEST, "size is not in the form width,height"); return; } } String where = null; double lo = Double.NaN; double hi = Double.NaN; int[] ramp = null; if (layerDefs != null) { final String[] tokens = m_patternSemiColon.split(layerDefs); for (final String token : tokens) { final String[] keyval = m_patternEqual.split(token.substring(2)); if (keyval.length == 2) { final String key = keyval[0]; final String val = keyval[1]; if ("lo".equalsIgnoreCase(key)) { lo = "NaN".equalsIgnoreCase(val) ? Double.NaN : Double.parseDouble(val); } else if ("hi".equalsIgnoreCase(key)) { hi = "NaN".equalsIgnoreCase(val) ? Double.NaN : Double.parseDouble(val); } else if ("ramp".equalsIgnoreCase(key)) { ramp = parseRamp(val); } else if ("where".equalsIgnoreCase(key)) { where = val; } } } } if (ramp == null) { ramp = new int[] { 0xFFFFFF, 0x000000 }; } final Range range = new Range(); final Map<Long, Double> map = query(where, xmin, ymin, xmax, ymax, range); if (!Double.isNaN(lo)) { range.lo = lo; } if (!Double.isNaN(hi)) { range.hi = hi; } range.dd = range.hi - range.lo; final int typeIntRgb = "true".equalsIgnoreCase(transparent) ? BufferedImage.TYPE_INT_ARGB : BufferedImage.TYPE_INT_RGB; BufferedImage bufferedImage = new BufferedImage(imageWidth, imageHeight, typeIntRgb); final Graphics2D graphics = bufferedImage.createGraphics(); try { graphics.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); graphics.setBackground(new Color(0, 0, 0, 0)); drawCells(graphics, imageWidth, imageHeight, xmin, ymin, xdel, ydel, range, ramp, map.entrySet()); } finally { graphics.dispose(); } // bufferedImage = m_op.filter(bufferedImage, null); final ByteArrayOutputStream baos = new ByteArrayOutputStream(10 * 1024); ImageIO.write(bufferedImage, "PNG", baos); response.setStatus(HttpServletResponse.SC_OK); response.setContentType("image/png"); response.setContentLength(baos.size()); baos.writeTo(response.getOutputStream()); response.getOutputStream().flush(); }
From source file:distribuidos.MyThread.java
private void enviarImgRaiz() { String imagepath = Main.imagen; String newimagepath = Main.newimagen; BufferedImage original = null; try {/*from ww w . j av a 2 s. com*/ original = ImageIO.read(new File(imagepath)); } catch (IOException ex) { Logger.getLogger(MyThread.class.getName()).log(Level.SEVERE, null, ex); } Graphics2D g2d = original.createGraphics(); g2d.setBackground(Color.WHITE); File f = new File(imagepath); try { ImageIO.write(original, "png", f); } catch (IOException ex) { Logger.getLogger(MyThread.class.getName()).log(Level.SEVERE, null, ex); } BufferedImage nueva = new BufferedImage(original.getWidth(), original.getHeight(), BufferedImage.TYPE_INT_ARGB); File fn = new File(newimagepath); try { ImageIO.write(nueva, "png", fn); } catch (IOException ex) { Logger.getLogger(MyThread.class.getName()).log(Level.SEVERE, null, ex); } int filacero = 0; int partes = this.nodo.getNhijos(); int filasporparte = nueva.getHeight() / partes; int resto = nueva.getHeight() % partes; Mensaje tochild = new Mensaje(this.idnode); tochild.setCabecera("Imagen"); tochild.setContenido(""); tochild.setStr1(imagepath); tochild.setStr2(newimagepath); Iterator it = this.nodo.getHijos(); int y = filacero; while (it.hasNext()) { tochild.setReceptor((int) it.next()); tochild.setAux1(0); tochild.setAux2(y); tochild.setAux3(nueva.getWidth()); tochild.setAux4(filasporparte + resto); System.out.println("Envio a hijo"); this.enviarMensaje(tochild); try { EMDijkstra.acquire(); } catch (InterruptedException ex) { Logger.getLogger(MyThread.class.getName()).log(Level.SEVERE, null, ex); } outDeficit++; //DIJKSTRA EMDijkstra.release(); y += filasporparte + resto; resto = 0; } }