List of usage examples for javax.imageio ImageIO write
public static boolean write(RenderedImage im, String formatName, OutputStream output) throws IOException
From source file:com.alehuo.wepas2016projekti.service.InitService.java
/** * Pienent kuvan/*from w w w. j a v a 2 s .c om*/ * * @param byteArray Kuvan data * @param type Kuvan tiedostotyyppi * @param widthHeight Leveys ja korkeus (Kuvat ovat nelin muotoisia) * @return Pienennetyn kuvan data */ public byte[] resizeImage(byte[] byteArray, String type, int widthHeight) { BufferedImage resized; try { resized = Scalr.resize(ImageIO.read(new ByteArrayInputStream(byteArray)), Scalr.Method.QUALITY, Scalr.Mode.FIT_TO_HEIGHT, widthHeight, widthHeight, Scalr.OP_ANTIALIAS); ByteArrayOutputStream baos = new ByteArrayOutputStream(); ImageIO.write(resized, type, baos); return baos.toByteArray(); } catch (IOException ex) { return null; } }
From source file:org.n52.io.type.quantity.handler.img.ChartIoHandler.java
@Override public void encodeAndWriteTo(DataCollection<Data<QuantityValue>> data, OutputStream stream) throws IoParseException { try {//from w w w . j a v a 2 s.com writeDataToChart(data); ImageIO.write(createImage(), mimeType.getFormatName(), stream); } catch (IOException e) { throw new IoParseException("Could not write image to output stream.", e); } }
From source file:org.javarebel.chart.ChartComponentListener.java
@Override public void beforePhase(PhaseEvent arg0) { FacesContext context = arg0.getFacesContext(); ExternalContext eCtx = context.getExternalContext(); HttpServletRequest req = (HttpServletRequest) eCtx.getRequest(); String data_KEY = req.getParameter("data_KEY"); logger.info("Chart Data Key is " + data_KEY); HttpSession session = req.getSession(); if (data_KEY != null) { Object chartData = session.getAttribute(data_KEY); if (chartData != null) { ChartData data = ChartData.class.cast(chartData); logger.info("Chart Type received is " + data.getType()); IChartGenerator chartGen = ChartGeneratorFactory.getChartGenerator(data.getType()); logger.info("ChartGenerator in use -> " + chartGen.getClass().getName()); JFreeChart chart = chartGen.generateChart(data); BufferedImage img = chart.createBufferedImage(Integer.valueOf(data.getWidth()), Integer.valueOf(data.getHeight())); try { HttpServletResponse response = (HttpServletResponse) eCtx.getResponse(); response.setContentType("image/png"); response.setHeader("Cache-Control", "no-store"); response.setHeader("Pragma", "no-cache"); response.setDateHeader("Expires", 0L); ServletOutputStream output = response.getOutputStream(); ImageIO.write(img, "png", output); session.removeAttribute(data_KEY); context.responseComplete(); } catch (Exception e) { logger.log(Level.SEVERE, e.getMessage(), e); throw new IllegalStateException(e); }//w w w . j a va 2s .c o m } } }
From source file:com.buession.cas.web.controller.CaptchaController.java
@Override protected ModelAndView handleRequestInternal(HttpServletRequest request, HttpServletResponse response) throws IOException { response.setContentType("image/jpg"); response.setHeader("Pragma", "no-cache"); response.setHeader("Cache-Control", "no-store, no-cache, must-revalidate"); response.setDateHeader("Expires", 0); String text = producer.createText(); captchaService.add(request, text);/*from w w w . ja v a 2s . co m*/ BufferedImage im = producer.createImage(text); ServletOutputStream out = response.getOutputStream(); ImageIO.write(im, "jpg", out); try { out.flush(); } finally { out.close(); } return null; }
From source file:vazkii.psi.client.core.helper.SharingHelper.java
public static String takeScreenshot() throws Exception { Minecraft mc = Minecraft.getMinecraft(); ScaledResolution res = new ScaledResolution(mc); int screenWidth = mc.displayWidth; int screenHeight = mc.displayHeight; int scale = res.getScaleFactor(); int width = 380 * scale; int height = 200 * scale; int left = screenWidth / 2 - width / 2; int top = screenHeight / 2 - height / 2; int i = width * height; if (pixelBuffer == null || pixelBuffer.capacity() < i) { pixelBuffer = BufferUtils.createIntBuffer(i); pixelValues = new int[i]; }/*from w w w . ja v a 2 s . c o m*/ GL11.glPixelStorei(GL11.GL_PACK_ALIGNMENT, 1); GL11.glPixelStorei(GL11.GL_UNPACK_ALIGNMENT, 1); pixelBuffer.clear(); GL11.glReadPixels(left, top, width, height, GL12.GL_BGRA, GL12.GL_UNSIGNED_INT_8_8_8_8_REV, (IntBuffer) pixelBuffer); pixelBuffer.get(pixelValues); TextureUtil.processPixelValues(pixelValues, width, height); BufferedImage bufferedimage = null; bufferedimage = new BufferedImage(width, height, 1); bufferedimage.setRGB(0, 0, width, height, pixelValues, 0, width); ByteArrayOutputStream stream = new ByteArrayOutputStream(); ImageIO.write(bufferedimage, "png", stream); byte[] bArray = stream.toByteArray(); String base64 = Base64.getEncoder().encodeToString(bArray); return base64; }
From source file:eu.planets_project.tb.impl.data.util.ImageThumbnail.java
/** * Create a scaled jpeg of an image. The width/height ratio is preserved. * /*from w ww .j a v a 2 s. c o m*/ * <p> * If image is smaller than thumbWidth x thumbHeight, it will be magnified, * otherwise it will be scaled down. * </p> * * @param image * the image to reduce * @param thumbWidth * the maximum width of the thumbnail * @param thumbHeight * the maximum heigth of the thumbnail * @param quality * the jpeg quality ot the thumbnail * @param out * a stream where the thumbnail data is written to */ public static void createThumb(Image image, int thumbWidth, int thumbHeight, OutputStream out) throws Exception { int imageWidth = image.getWidth(null); int imageHeight = image.getHeight(null); double thumbRatio = (double) thumbWidth / (double) thumbHeight; double imageRatio = (double) imageWidth / (double) imageHeight; if (thumbRatio < imageRatio) { thumbHeight = (int) (thumbWidth / imageRatio); } else { thumbWidth = (int) (thumbHeight * imageRatio); } // draw original image to thumbnail image object and // scale it to the new size on-the-fly BufferedImage thumbImage = new BufferedImage(thumbWidth, thumbHeight, BufferedImage.TYPE_INT_ARGB); Graphics2D graphics2D = thumbImage.createGraphics(); graphics2D.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BICUBIC); graphics2D.setRenderingHint(RenderingHints.KEY_ALPHA_INTERPOLATION, RenderingHints.VALUE_ALPHA_INTERPOLATION_QUALITY); graphics2D.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); graphics2D.drawImage(image, 0, 0, thumbWidth, thumbHeight, null); // save thumbnail image to out stream log.debug("Start writing rescaled image..."); ImageIO.write(thumbImage, "png", out); log.debug("DONE writing rescaled image..."); }
From source file:nc.noumea.mairie.organigramme.services.exportGraphML.impl.AbstractExportGraphMLService.java
/** * Permet d'ajouter le logo de la mairie au fichier d'export * //from w w w.jav a2 s . co m * @param graph * : l'lment graph * @throws IOException * : si le logo ne peux pas tre lu ou ajout au fichier */ protected void ajoutLogoMairie(Element graph) throws IOException { Element elKeyResource = graph.getParent().addElement("data").addAttribute("key", "d13"); Element elResource = elKeyResource.addElement("y:Resources").addElement("y:Resource"); elResource.addAttribute("id", "1").addAttribute("type", "java.awt.image.BufferedImage"); InputStream is = this.getClass().getClassLoader().getResourceAsStream("logo-mairie.jpg"); BufferedImage img = ImageIO.read(is); ByteArrayOutputStream baos = new ByteArrayOutputStream(); ImageIO.write(img, "jpg", baos); baos.flush(); String encodedImage = Base64.encodeBase64String(baos.toByteArray()); baos.close(); elResource.setText(encodedImage); Element el = graph.addElement("node").addAttribute("id", "0"); Element elD6 = el.addElement("data").addAttribute("key", "d6"); Element elImageNode = elD6.addElement("y:ImageNode"); elImageNode.addElement("y:Geometry").addAttribute("height", "136.3").addAttribute("width", "143.0") .addAttribute("x", "256.0").addAttribute("y", "-291.0"); elImageNode.addElement("y:Image").addAttribute("alphaImage", "true").addAttribute("refid", "1"); }
From source file:Trabalho.HistogramaHSB.java
public ChartPanel criaHistograma() throws IOException { //pega a imagem BufferedImage img = pegaImagem(); //w pega a largura da imagem - h pega a altura da imagem int w = img.getWidth(); int h = img.getHeight(); //d calcula o tamanho da imagem int d = (w * h); //red, green e blue iro receber os tons de cor antigo da imagem - u vai receber o RGB da cor int red, green, blue, u; //retorna rgb no mtodo float[] hsb;//from w w w. j av a2 s .c o m int[] vetH = new int[256]; int[] vetS = new int[256]; int[] vetB = new int[256]; float hue, sat, bri; //cAux e oldColor pegam os tons originais da imagem - newColor pega os tons aps o clculo Color oldColor; Color newColor; //for responsvel por substituir os tons antigos pelos novos; percorrem a imagem por largura e altura for (int i = 0; i < w; i++) { for (int j = 0; j < h; j++) { u = img.getRGB(i, j); //u vai receber o RGB da posio i, j oldColor = new Color(u); //oldColor instanciado e recebe o valor de u //cada cor recebe o valor do tom original red = oldColor.getRed(); green = oldColor.getGreen(); blue = oldColor.getBlue(); hsb = Color.RGBtoHSB(red, green, blue, null); hue = hsb[0]; sat = hsb[1]; bri = hsb[2]; // System.out.println("RGB [" + red + "," + green + "," + blue + "] converted to HSB [" + hue + "," + sat + "," + bri + "]"); // hue = hue * 360; // int convH = Integer.valueOf(new Float(hue).intValue()); // vetH[convH]++; // // sat = sat * 100; // int convS = Integer.valueOf(new Float(sat).intValue()); // vetS[convS]++; // // bri = bri * 100; // int convB = Integer.valueOf(new Float(bri).intValue()); // vetB[convB]++; newColor = new Color(hue, sat, bri); //seta o RGB da imagem nas posies i, j pegando os valores da newColor img.setRGB(i, j, newColor.getRGB()); } } File ouptut = new File("D:\\ProjetosNetBeans\\PDI\\src\\imagens\\5.jpeg"); ImageIO.write(img, "png", ouptut); dataset = new HistogramDataset(); //pega o RGB r = raster.getSamples(0, 0, w, h, 0, r); dataset.addSeries("Red", r, 360); r = raster.getSamples(0, 0, w, h, 1, r); dataset.addSeries("Green", r, 101); r = raster.getSamples(0, 0, w, h, 2, r); dataset.addSeries("Blue", r, 101); JFreeChart chart = ChartFactory.createHistogram("Histograma", "Pixels", "Y", dataset, PlotOrientation.VERTICAL, true, true, false); //Plota as cores XYPlot plot = (XYPlot) chart.getPlot(); renderer = (XYBarRenderer) plot.getRenderer(); renderer.setBarPainter(new StandardXYBarPainter()); //vermelho, verde, azul Paint[] paintArray = { new Color(0x80ff0000, true), new Color(0x8000ff00, true), new Color(0x800000ff, true) }; //desenhando o grfico plot.setDrawingSupplier( new DefaultDrawingSupplier(paintArray, DefaultDrawingSupplier.DEFAULT_FILL_PAINT_SEQUENCE, DefaultDrawingSupplier.DEFAULT_OUTLINE_PAINT_SEQUENCE, DefaultDrawingSupplier.DEFAULT_STROKE_SEQUENCE, DefaultDrawingSupplier.DEFAULT_OUTLINE_STROKE_SEQUENCE, DefaultDrawingSupplier.DEFAULT_SHAPE_SEQUENCE)); ChartPanel panel = new ChartPanel(chart); panel.setMouseWheelEnabled(true); return panel; }
From source file:UploadImage.java
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // change the following parameters to connect to the oracle database String username = "lingbo"; String password = "TlboSci1994"; String drivername = "oracle.jdbc.driver.OracleDriver"; String dbstring = "jdbc:oracle:thin:@gwynne.cs.ualberta.ca:1521:CRS"; int pic_id;//from w w w .j a va2s . c o m try { //Parse the HTTP request to get the image stream DiskFileUpload fu = new DiskFileUpload(); List FileItems = fu.parseRequest(request); // Process the uploaded items, assuming only 1 image file uploaded Iterator i = FileItems.iterator(); FileItem item = (FileItem) i.next(); while (i.hasNext() && item.isFormField()) { item = (FileItem) i.next(); } //Get the image stream InputStream instream = item.getInputStream(); BufferedImage img = ImageIO.read(instream); BufferedImage thumbNail = shrink(img, 10); // Connect to the database and create a statement Connection conn = getConnected(drivername, dbstring, username, password); Statement stmt = conn.createStatement(); /* * First, to generate a unique pic_id using an SQL sequence */ ResultSet rset1 = stmt.executeQuery("SELECT pic_id_sequence.nextval from dual"); rset1.next(); pic_id = rset1.getInt(1); //Insert an empty blob into the table first. Note that you have to //use the Oracle specific function empty_blob() to create an empty blob stmt.execute("INSERT INTO pictures VALUES(" + pic_id + ",'test',empty_blob())"); // to retrieve the lob_locator // Note that you must use "FOR UPDATE" in the select statement String cmd = "SELECT * FROM pictures WHERE pic_id = " + pic_id + " FOR UPDATE"; ResultSet rset = stmt.executeQuery(cmd); rset.next(); BLOB myblob = ((OracleResultSet) rset).getBLOB(3); //Write the image to the blob object OutputStream outstream = myblob.setBinaryStream(1); ImageIO.write(thumbNail, "jpg", outstream); /* int size = myblob.getBufferSize(); byte[] buffer = new byte[size]; int length = -1; while ((length = instream.read(buffer)) != -1) outstream.write(buffer, 0, length); */ instream.close(); outstream.close(); stmt.executeUpdate("commit"); response_message = " Upload OK! "; conn.close(); } catch (Exception ex) { //System.out.println( ex.getMessage()); response_message = ex.getMessage(); } //Output response to the client response.setContentType("text/html"); PrintWriter out = response.getWriter(); out.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0 " + "Transitional//EN\">\n" + "<HTML>\n" + "<HEAD><TITLE>Upload Message</TITLE></HEAD>\n" + "<BODY>\n" + "<H1>" + response_message + "</H1>\n" + "</BODY></HTML>"); }
From source file:com.igormaznitsa.mindmap.exporters.PNGImageExporter.java
@Override public void doExport(final MindMapPanel panel, final JComponent options, final OutputStream out) throws IOException { for (final Component compo : ((JPanel) options).getComponents()) { if (compo instanceof JCheckBox) { final JCheckBox cb = (JCheckBox) compo; if ("unfold".equalsIgnoreCase(cb.getActionCommand())) { flagExpandAllNodes = cb.isSelected(); } else if ("back".equalsIgnoreCase(cb.getActionCommand())) { flagSaveBackground = cb.isSelected(); }//w w w . j a v a2 s . c o m } } final MindMapPanelConfig newConfig = new MindMapPanelConfig(panel.getConfiguration(), false); newConfig.setDrawBackground(flagSaveBackground); newConfig.setScale(1.0f); final RenderedImage image = MindMapPanel.renderMindMapAsImage(panel.getModel(), newConfig, flagExpandAllNodes); if (image == null) { if (out == null) { LOGGER.error("Can't render map as image"); panel.getController().getDialogProvider(panel) .msgError(BUNDLE.getString("PNGImageExporter.msgErrorDuringRendering")); return; } else { throw new IOException("Can't render image"); } } final ByteArrayOutputStream buff = new ByteArrayOutputStream(128000); ImageIO.write(image, "png", buff);//NOI18N final byte[] imageData = buff.toByteArray(); File fileToSaveMap = null; OutputStream theOut = out; if (theOut == null) { fileToSaveMap = selectFileForFileFilter(panel, BUNDLE.getString("PNGImageExporter.saveDialogTitle"), ".png", BUNDLE.getString("PNGImageExporter.filterDescription"), BUNDLE.getString("PNGImageExporter.approveButtonText")); fileToSaveMap = checkFileAndExtension(panel, fileToSaveMap, ".png");//NOI18N theOut = fileToSaveMap == null ? null : new BufferedOutputStream(new FileOutputStream(fileToSaveMap, false)); } if (theOut != null) { try { IOUtils.write(imageData, theOut); } finally { if (fileToSaveMap != null) { IOUtils.closeQuietly(theOut); } } } }