List of usage examples for java.awt.image BufferedImage createGraphics
public Graphics2D createGraphics()
From source file:edu.ku.brc.ui.GraphicsUtils.java
/** * @param bufImg//w w w . jav a 2 s . com * @param size * @return */ public static BufferedImage generateScaledImage(final BufferedImage bufImg, @SuppressWarnings("unused") final Object hintsArg, final int size) { BufferedImage sourceImage = bufImg; int srcWidth = sourceImage.getWidth(); int srcHeight = sourceImage.getHeight(); double longSideForSource = Math.max(srcWidth, srcHeight); double longSideForDest = size; double multiplier = longSideForDest / longSideForSource; int destWidth = (int) (srcWidth * multiplier); int destHeight = (int) (srcHeight * multiplier); BufferedImage destImage = null; destImage = new BufferedImage(destWidth, destHeight, BufferedImage.TYPE_INT_RGB); Graphics2D graphics2D = destImage.createGraphics(); graphics2D.drawImage(sourceImage, 0, 0, destWidth, destHeight, null); graphics2D.dispose(); return destImage; }
From source file:com.simiacryptus.util.Util.java
/** * To image buffered image.//w w w .j a v a 2s .c om * * @param component the component * @return the buffered image */ public static BufferedImage toImage(@javax.annotation.Nonnull final Component component) { try { com.simiacryptus.util.Util.layout(component); @javax.annotation.Nonnull final BufferedImage img = new BufferedImage(component.getWidth(), component.getHeight(), BufferedImage.TYPE_INT_ARGB_PRE); final Graphics2D g = img.createGraphics(); g.setColor(component.getForeground()); g.setFont(component.getFont()); component.print(g); return img; } catch (@javax.annotation.Nonnull final Exception e) { return null; } }
From source file:edu.ku.brc.ui.GraphicsUtils.java
/** * @param name//w w w .j ava2s .c o m * @param imgIcon * @return */ public static String uuencodeImage(final String name, final ImageIcon imgIcon) { try { BufferedImage tmp = new BufferedImage(imgIcon.getIconWidth(), imgIcon.getIconWidth(), BufferedImage.TYPE_INT_ARGB); Graphics2D g2 = tmp.createGraphics(); //g2.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR); g2.drawImage(imgIcon.getImage(), 0, 0, imgIcon.getIconWidth(), imgIcon.getIconWidth(), null); g2.dispose(); ByteArrayOutputStream output = new ByteArrayOutputStream(8192); ImageIO.write(tmp, "PNG", output); byte[] outputBytes = output.toByteArray(); output.close(); ByteArrayOutputStream bos = new ByteArrayOutputStream(); UUEncoder uuencode = new UUEncoder(name); uuencode.encode(new ByteArrayInputStream(outputBytes), bos); return bos.toString(); } catch (Exception ex) { edu.ku.brc.af.core.UsageTracker.incrHandledUsageCount(); edu.ku.brc.exceptions.ExceptionTracker.getInstance().capture(GraphicsUtils.class, ex); ex.printStackTrace(); } return ""; }
From source file:com.aimluck.eip.fileupload.util.FileuploadUtils.java
public static BufferedImage transformImage(BufferedImage image, AffineTransform transform, int newWidth, int newHeight) throws Exception { AffineTransformOp op = new AffineTransformOp(transform, AffineTransformOp.TYPE_BICUBIC); BufferedImage destinationImage = new BufferedImage(newWidth, newHeight, image.getType()); Graphics2D g = destinationImage.createGraphics(); g.setColor(Color.WHITE);/*ww w . ja v a 2 s . c om*/ destinationImage = op.filter(image, destinationImage); return destinationImage; }
From source file:ImageUtil.java
/** * Creates a scaled copy of the source image. * // w ww. j av a 2s .c o m * @param src * source image to be scaled * @param width * the width for the new scaled image in pixels * @param height * the height for the new scaled image in pixels * @return a copy of the source image scaled to <tt>width</tt> x * <tt>height</tt> pixels. */ public static BufferedImage scaleImage(BufferedImage src, int width, int height) { Image scaled = src.getScaledInstance(width, height, 0); BufferedImage ret = null; /* * ColorModel cm = src.getColorModel(); if (cm instanceof * IndexColorModel) { ret = new BufferedImage( width, height, * src.getType(), (IndexColorModel) cm ); } else { ret = new * BufferedImage( src.getWidth(), src.getHeight(), src.getType() ); } * Graphics2D g = ret.createGraphics(); //clear alpha channel Composite * comp = g.getComposite(); * g.setComposite(AlphaComposite.getInstance(AlphaComposite.CLEAR, * 0.0f)); Rectangle2D.Double d = new * Rectangle2D.Double(0,0,ret.getWidth(),ret.getHeight()); g.fill(d); * g.setComposite(comp); */ ret = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB); Graphics2D g = ret.createGraphics(); // copy image g.drawImage(scaled, 0, 0, null); return ret; }
From source file:com.aimluck.eip.fileupload.util.FileuploadUtils.java
/** * ???/*from w ww.j av a2 s . c o m*/ * * @param imgfile * @param width * @param height * @return */ public static BufferedImage shrinkAndTrimImage(BufferedImage imgfile, int width, int height) { int iwidth = imgfile.getWidth(); int iheight = imgfile.getHeight(); double ratio = Math.max((double) width / (double) iwidth, (double) height / (double) iheight); int shrinkedWidth; int shrinkedHeight; if ((iwidth <= width) || (iheight < height)) { shrinkedWidth = iwidth; shrinkedHeight = iheight; } else { shrinkedWidth = (int) (iwidth * ratio); shrinkedHeight = (int) (iheight * ratio); } // ?? Image targetImage = imgfile.getScaledInstance(shrinkedWidth, shrinkedHeight, Image.SCALE_AREA_AVERAGING); int w_size = targetImage.getWidth(null); int h_size = targetImage.getHeight(null); if (targetImage.getWidth(null) < width) { w_size = width; } if (targetImage.getHeight(null) < height) { h_size = height; } BufferedImage tmpImage = new BufferedImage(w_size, h_size, BufferedImage.TYPE_INT_RGB); Graphics2D g = tmpImage.createGraphics(); g.setBackground(Color.WHITE); g.setColor(Color.WHITE); // ?????????????? g.fillRect(0, 0, w_size, h_size); int diff_w = 0; int diff_h = 0; if (width > shrinkedWidth) { diff_w = (width - shrinkedWidth) / 2; } if (height > shrinkedHeight) { diff_h = (height - shrinkedHeight) / 2; } g.drawImage(targetImage, diff_w, diff_h, null); int _iwidth = tmpImage.getWidth(); int _iheight = tmpImage.getHeight(); BufferedImage _tmpImage; if (_iwidth > _iheight) { int diff = _iwidth - width; _tmpImage = tmpImage.getSubimage(diff / 2, 0, width, height); } else { int diff = _iheight - height; _tmpImage = tmpImage.getSubimage(0, diff / 2, width, height); } return _tmpImage; }
From source file:snapshot.java
public static Object respond(final RequestHeader header, serverObjects post, final serverSwitch env) { final Switchboard sb = (Switchboard) env; final serverObjects defaultResponse = new serverObjects(); final boolean authenticated = sb.adminAuthenticated(header) >= 2; final String ext = header.get(HeaderFramework.CONNECTION_PROP_EXT, ""); if (ext.isEmpty()) { throw new TemplateProcessingException( "Missing extension. Try with rss, xml, json, pdf, png or jpg." + ext, HttpStatus.SC_BAD_REQUEST); }//w w w . j a v a 2 s. c o m if (ext.equals("rss")) { // create a report about the content of the snapshot directory if (!authenticated) { defaultResponse.authenticationRequired(); return defaultResponse; } int maxcount = post == null ? 10 : post.getInt("maxcount", 10); int depthx = post == null ? -1 : post.getInt("depth", -1); Integer depth = depthx == -1 ? null : depthx; String orderx = post == null ? "ANY" : post.get("order", "ANY"); Snapshots.Order order = Snapshots.Order.valueOf(orderx); String statex = post == null ? Transactions.State.INVENTORY.name() : post.get("state", Transactions.State.INVENTORY.name()); Transactions.State state = Transactions.State.valueOf(statex); String host = post == null ? null : post.get("host"); Map<String, Revisions> iddate = Transactions.select(host, depth, order, maxcount, state); // now select the URL from the index for these ids in iddate and make an RSS feed RSSFeed rssfeed = new RSSFeed(Integer.MAX_VALUE); rssfeed.setChannel(new RSSMessage("Snapshot list for host = " + host + ", depth = " + depth + ", order = " + order + ", maxcount = " + maxcount, "", "")); for (Map.Entry<String, Revisions> e : iddate.entrySet()) { try { DigestURL u = e.getValue().url == null ? sb.index.fulltext().getURL(e.getKey()) : new DigestURL(e.getValue().url); if (u == null) continue; RSSMessage message = new RSSMessage(u.toNormalform(true), "", u, e.getKey()); message.setPubDate(e.getValue().dates[0]); rssfeed.addMessage(message); } catch (IOException ee) { ConcurrentLog.logException(ee); } } byte[] rssBinary = UTF8.getBytes(rssfeed.toString()); return new ByteArrayInputStream(rssBinary); } // for the following methods we (mostly) need an url or a url hash if (post == null) post = new serverObjects(); final boolean xml = ext.equals("xml"); final boolean pdf = ext.equals("pdf"); if (pdf && !authenticated) { defaultResponse.authenticationRequired(); return defaultResponse; } final boolean pngjpg = ext.equals("png") || ext.equals(DEFAULT_EXT); String urlhash = post.get("urlhash", ""); String url = post.get("url", ""); DigestURL durl = null; if (urlhash.length() == 0 && url.length() > 0) { try { durl = new DigestURL(url); urlhash = ASCII.String(durl.hash()); } catch (MalformedURLException e) { } } if (durl == null && urlhash.length() > 0) { try { durl = sb.index.fulltext().getURL(urlhash); } catch (IOException e) { ConcurrentLog.logException(e); } } if (ext.equals("json")) { // command interface: view and change a transaction state, get metadata about transactions in the past String command = post.get("command", "metadata"); String statename = post.get("state"); JSONObject result = new JSONObject(); try { if (command.equals("status")) { // return a status of the transaction archive JSONObject sizes = new JSONObject(); for (Map.Entry<String, Integer> state : Transactions.sizes().entrySet()) sizes.put(state.getKey(), state.getValue()); result.put("size", sizes); } else if (command.equals("list")) { if (!authenticated) { defaultResponse.authenticationRequired(); return defaultResponse; } // return a status of the transaction archive String host = post.get("host"); String depth = post.get("depth"); int depthi = depth == null ? -1 : Integer.parseInt(depth); for (Transactions.State state : statename == null ? new Transactions.State[] { Transactions.State.INVENTORY, Transactions.State.ARCHIVE } : new Transactions.State[] { Transactions.State.valueOf(statename) }) { if (host == null) { JSONObject hostCountInventory = new JSONObject(); for (String h : Transactions.listHosts(state)) { int size = Transactions.listIDsSize(h, depthi, state); if (size > 0) hostCountInventory.put(h, size); } result.put("count." + state.name(), hostCountInventory); } else { TreeMap<Integer, Collection<Revisions>> ids = Transactions.listIDs(host, depthi, state); if (ids == null) { result.put("result", "fail"); result.put("comment", "no entries for host " + host + " found"); } else { for (Map.Entry<Integer, Collection<Revisions>> entry : ids.entrySet()) { for (Revisions r : entry.getValue()) { try { JSONObject metadata = new JSONObject(); DigestURL u = r.url != null ? new DigestURL(r.url) : sb.index.fulltext().getURL(r.urlhash); metadata.put("url", u == null ? "unknown" : u.toNormalform(true)); metadata.put("dates", r.dates); assert r.depth == entry.getKey().intValue(); metadata.put("depth", entry.getKey().intValue()); result.put(r.urlhash, metadata); } catch (IOException e) { } } } } } } } else if (command.equals("commit")) { if (!authenticated) { defaultResponse.authenticationRequired(); return defaultResponse; } Revisions r = Transactions.commit(urlhash); if (r != null) { result.put("result", "success"); result.put("depth", r.depth); result.put("url", r.url); result.put("dates", r.dates); } else { result.put("result", "fail"); } result.put("urlhash", urlhash); } else if (command.equals("rollback")) { if (!authenticated) { defaultResponse.authenticationRequired(); return defaultResponse; } Revisions r = Transactions.rollback(urlhash); if (r != null) { result.put("result", "success"); result.put("depth", r.depth); result.put("url", r.url); result.put("dates", r.dates); } else { result.put("result", "fail"); } result.put("urlhash", urlhash); } else if (command.equals("metadata")) { try { Revisions r; Transactions.State state = statename == null || statename.length() == 0 ? null : Transactions.State.valueOf(statename); if (state == null) { r = Transactions.getRevisions(Transactions.State.INVENTORY, urlhash); if (r != null) state = Transactions.State.INVENTORY; r = Transactions.getRevisions(Transactions.State.ARCHIVE, urlhash); if (r != null) state = Transactions.State.ARCHIVE; } else { r = Transactions.getRevisions(state, urlhash); } if (r != null) { JSONObject metadata = new JSONObject(); DigestURL u; u = r.url != null ? new DigestURL(r.url) : sb.index.fulltext().getURL(r.urlhash); metadata.put("url", u == null ? "unknown" : u.toNormalform(true)); metadata.put("dates", r.dates); metadata.put("depth", r.depth); metadata.put("state", state.name()); result.put(r.urlhash, metadata); } } catch (IOException | IllegalArgumentException e) { } } } catch (JSONException e) { ConcurrentLog.logException(e); } String json = result.toString(); if (post.containsKey("callback")) json = post.get("callback") + "([" + json + "]);"; return new ByteArrayInputStream(UTF8.getBytes(json)); } // for the following methods we always need the durl to fetch data if (durl == null) { throw new TemplateMissingParameterException("Missing valid url or urlhash parameter"); } if (xml) { Collection<File> xmlSnapshots = Transactions.findPaths(durl, "xml", Transactions.State.ANY); File xmlFile = null; if (xmlSnapshots.isEmpty()) { throw new TemplateProcessingException("Could not find the xml snapshot file.", HttpStatus.SC_NOT_FOUND); } xmlFile = xmlSnapshots.iterator().next(); try { byte[] xmlBinary = FileUtils.read(xmlFile); return new ByteArrayInputStream(xmlBinary); } catch (final IOException e) { ConcurrentLog.logException(e); throw new TemplateProcessingException("Could not read the xml snapshot file."); } } if (pdf || pngjpg) { Collection<File> pdfSnapshots = Transactions.findPaths(durl, "pdf", Transactions.State.INVENTORY); File pdfFile = null; if (pdfSnapshots.isEmpty()) { // if the client is authenticated, we create the pdf on the fly! if (!authenticated) { throw new TemplateProcessingException( "Could not find the pdf snapshot file. You must be authenticated to generate one on the fly.", HttpStatus.SC_NOT_FOUND); } SolrDocument sd = sb.index.fulltext().getMetadata(durl.hash()); boolean success = false; if (sd == null) { success = Transactions.store(durl, new Date(), 99, false, true, sb.getConfigBool(SwitchboardConstants.PROXY_TRANSPARENT_PROXY, false) ? "http://127.0.0.1:" + sb.getConfigInt(SwitchboardConstants.SERVER_PORT, 8090) : null, sb.getConfig("crawler.http.acceptLanguage", null)); } else { SolrInputDocument sid = sb.index.fulltext().getDefaultConfiguration().toSolrInputDocument(sd); success = Transactions.store(sid, false, true, true, sb.getConfigBool(SwitchboardConstants.PROXY_TRANSPARENT_PROXY, false) ? "http://127.0.0.1:" + sb.getConfigInt(SwitchboardConstants.SERVER_PORT, 8090) : null, sb.getConfig("crawler.http.acceptLanguage", null)); } if (success) { pdfSnapshots = Transactions.findPaths(durl, "pdf", Transactions.State.ANY); if (!pdfSnapshots.isEmpty()) { pdfFile = pdfSnapshots.iterator().next(); } } } else { pdfFile = pdfSnapshots.iterator().next(); } if (pdfFile == null) { throw new TemplateProcessingException( "Could not find the pdf snapshot file and could not generate one on the fly.", HttpStatus.SC_NOT_FOUND); } if (pdf) { try { byte[] pdfBinary = FileUtils.read(pdfFile); return new ByteArrayInputStream(pdfBinary); } catch (final IOException e) { ConcurrentLog.logException(e); throw new TemplateProcessingException("Could not read the pdf snapshot file."); } } if (pngjpg) { int width = Math.min(post.getInt("width", DEFAULT_WIDTH), DEFAULT_WIDTH); int height = Math.min(post.getInt("height", DEFAULT_HEIGHT), DEFAULT_HEIGHT); String imageFileStub = pdfFile.getAbsolutePath(); imageFileStub = imageFileStub.substring(0, imageFileStub.length() - 3); // cut off extension File imageFile = new File(imageFileStub + DEFAULT_WIDTH + "." + DEFAULT_HEIGHT + "." + ext); if (!imageFile.exists() && authenticated) { if (!Html2Image.pdf2image(pdfFile, imageFile, DEFAULT_WIDTH, DEFAULT_HEIGHT, DEFAULT_DENSITY, DEFAULT_QUALITY)) { throw new TemplateProcessingException( "Could not generate the " + ext + " image snapshot file."); } } if (!imageFile.exists()) { throw new TemplateProcessingException( "Could not find the " + ext + " image snapshot file. You must be authenticated to generate one on the fly.", HttpStatus.SC_NOT_FOUND); } if (width == DEFAULT_WIDTH && height == DEFAULT_HEIGHT) { try { byte[] imageBinary = FileUtils.read(imageFile); return new ByteArrayInputStream(imageBinary); } catch (final IOException e) { ConcurrentLog.logException(e); throw new TemplateProcessingException( "Could not read the " + ext + " image snapshot file."); } } // lets read the file and scale Image image; try { image = ImageParser.parse(imageFile.getAbsolutePath(), FileUtils.read(imageFile)); if (image == null) { throw new TemplateProcessingException( "Could not parse the " + ext + " image snapshot file."); } final Image scaled = image.getScaledInstance(width, height, Image.SCALE_AREA_AVERAGING); final MediaTracker mediaTracker = new MediaTracker(new Container()); mediaTracker.addImage(scaled, 0); try { mediaTracker.waitForID(0); } catch (final InterruptedException e) { } /* * Ensure there is no alpha component on the ouput image, as it is pointless * here and it is not well supported by the JPEGImageWriter from OpenJDK */ BufferedImage scaledBufferedImg = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB); scaledBufferedImg.createGraphics().drawImage(scaled, 0, 0, width, height, null); return new EncodedImage(scaledBufferedImg, ext, true); } catch (final IOException e) { ConcurrentLog.logException(e); throw new TemplateProcessingException("Could not scale the " + ext + " image snapshot file."); } } } throw new TemplateProcessingException( "Unsupported extension : " + ext + ". Try with rss, xml, json, pdf, png or jpg.", HttpStatus.SC_BAD_REQUEST); }
From source file:com.piaoyou.util.ImageUtil.java
/** * @todo: xem lai ham nay, neu kich thuoc nho hon max thi ta luu truc tiep * inputStream xuong thumbnailFile luon * * This method create a thumbnail and reserve the ratio of the output image * NOTE: This method closes the inputStream after it have done its work. * * @param inputStream the stream of a jpeg file * @param outputStream the output stream * @param maxWidth the maximum width of the image * @param maxHeight the maximum height of the image * @throws IOException/*from w w w.j a va2 s. com*/ * @throws BadInputException */ public static void createThumbnail(InputStream inputStream, OutputStream outputStream, int maxWidth, int maxHeight) throws IOException { if (inputStream == null) { throw new IllegalArgumentException("inputStream must not be null."); } if (outputStream == null) { throw new IllegalArgumentException("outputStream must not be null."); } //boolean useSun = false; if (maxWidth <= 0) { throw new IllegalArgumentException("maxWidth must >= 0"); } if (maxHeight <= 0) { throw new IllegalArgumentException("maxHeight must >= 0"); } try { //JPEGImageDecoder decoder = JPEGCodec.createJPEGDecoder(inputStream); //BufferedImage srcImage = decoder.decodeAsBufferedImage(); byte[] srcByte = FileUtil.getBytes(inputStream); InputStream is = new ByteArrayInputStream(srcByte); //ImageIcon imageIcon = new ImageIcon(srcByte); //Image srcImage = imageIcon.getImage(); BufferedImage srcImage = ImageIO.read(is); if (srcImage == null) { throw new IOException("Cannot decode image. Please check your file again."); } int imgWidth = srcImage.getWidth(); int imgHeight = srcImage.getHeight(); // imgWidth or imgHeight could be -1, which is considered as an assertion AssertionUtil.doAssert((imgWidth > 0) && (imgHeight > 0), "Assertion: ImageUtil: cannot get the image size."); // Set the scale. AffineTransform tx = new AffineTransform(); if ((imgWidth > maxWidth) || (imgHeight > maxHeight)) { double scaleX = (double) maxWidth / imgWidth; double scaleY = (double) maxHeight / imgHeight; double scaleRatio = (scaleX < scaleY) ? scaleX : scaleY; imgWidth = (int) (imgWidth * scaleX); imgWidth = (imgWidth == 0) ? 1 : imgWidth; imgHeight = (int) (imgHeight * scaleY); imgHeight = (imgHeight == 0) ? 1 : imgHeight; // scale as needed tx.scale(scaleRatio, scaleRatio); } else {// we don't need any transform here, just save it to file and return outputStream.write(srcByte); return; } // create thumbnail image BufferedImage bufferedImage = new BufferedImage(imgWidth, imgHeight, BufferedImage.TYPE_INT_RGB); Graphics2D g = bufferedImage.createGraphics(); boolean useTransform = false; if (useTransform) {// use transfrom to draw //log.trace("use transform"); g.drawImage(srcImage, tx, null); } else {// use java filter //log.trace("use filter"); Image scaleImage = getScaledInstance(srcImage, imgWidth, imgHeight); g.drawImage(scaleImage, 0, 0, null); } g.dispose();// free resource // write it to outputStream // JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(outputStream); // encoder.encode(bufferedImage); ImageIO.write(bufferedImage, "jpeg", outputStream); } catch (IOException e) { log.error("Error", e); throw e; } finally {// this finally is very important try { inputStream.close(); } catch (IOException e) { /* ignore */ e.printStackTrace(); } try { outputStream.close(); } catch (IOException e) {/* ignore */ e.printStackTrace(); } } }
From source file:at.tugraz.sss.serv.SSFileU.java
public static void scalePNGAndWrite(final BufferedImage buffImage, final String pngFilePath, final Integer width, final Integer height) throws IOException { final BufferedImage scaledThumb = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB); final Graphics2D graphics2D = scaledThumb.createGraphics(); graphics2D.setComposite(AlphaComposite.Src); graphics2D.drawImage(buffImage, 0, 0, width, height, null); graphics2D.dispose();//from w ww . j av a 2 s . c o m ImageIO.write(scaledThumb, SSFileExtE.png.toString(), new File(pngFilePath)); }
From source file:com.android.hierarchyviewerlib.device.DeviceBridge.java
private static boolean readLayer(DataInputStream in, PsdFile psd) { try {/* ww w. jav a 2 s . c o m*/ if (in.read() == 2) { return false; } String name = in.readUTF(); boolean visible = in.read() == 1; int x = in.readInt(); int y = in.readInt(); int dataSize = in.readInt(); byte[] data = new byte[dataSize]; int read = 0; while (read < dataSize) { read += in.read(data, read, dataSize - read); } ByteArrayInputStream arrayIn = new ByteArrayInputStream(data); BufferedImage chunk = ImageIO.read(arrayIn); // Ensure the image is in the right format BufferedImage image = new BufferedImage(chunk.getWidth(), chunk.getHeight(), BufferedImage.TYPE_INT_ARGB); Graphics2D g = image.createGraphics(); g.drawImage(chunk, null, 0, 0); g.dispose(); psd.addLayer(name, image, new Point(x, y), visible); return true; } catch (Exception e) { return false; } }