List of usage examples for java.awt Image getWidth
public abstract int getWidth(ImageObserver observer);
From source file:org.sbs.util.ImageCompress.java
/** * gif//from www . ja v a 2 s .c om * * @param originalFile * * @param resizedFile * ? * @param newWidth * * @param newHeight * -1? * @param quality * () * @throws IOException */ public void resize(File originalFile, File resizedFile, int newWidth, int newHeight, float quality) throws IOException { if (quality < 0 || quality > 1) { throw new IllegalArgumentException("Quality has to be between 0 and 1"); } ImageIcon ii = new ImageIcon(originalFile.getCanonicalPath()); Image i = ii.getImage(); Image resizedImage = null; int iWidth = i.getWidth(null); int iHeight = i.getHeight(null); if (newHeight == -1) { if (iWidth > iHeight) { resizedImage = i.getScaledInstance(newWidth, (newWidth * iHeight) / iWidth, Image.SCALE_SMOOTH); } else { resizedImage = i.getScaledInstance((newWidth * iWidth) / iHeight, newWidth, Image.SCALE_SMOOTH); } } else { resizedImage = i.getScaledInstance(newWidth, newHeight, Image.SCALE_SMOOTH); } // This code ensures that all the pixels in the image are loaded. Image temp = new ImageIcon(resizedImage).getImage(); // Create the buffered image. BufferedImage bufferedImage = new BufferedImage(temp.getWidth(null), temp.getHeight(null), BufferedImage.TYPE_INT_RGB); // Copy image to buffered image. Graphics g = bufferedImage.createGraphics(); // Clear background and paint the image. g.setColor(Color.white); g.fillRect(0, 0, temp.getWidth(null), temp.getHeight(null)); g.drawImage(temp, 0, 0, null); g.dispose(); // Soften. float softenFactor = 0.05f; float[] softenArray = { 0, softenFactor, 0, softenFactor, 1 - (softenFactor * 4), softenFactor, 0, softenFactor, 0 }; Kernel kernel = new Kernel(3, 3, softenArray); ConvolveOp cOp = new ConvolveOp(kernel, ConvolveOp.EDGE_NO_OP, null); bufferedImage = cOp.filter(bufferedImage, null); // Write the jpeg to a file. FileOutputStream out = FileUtils.openOutputStream(resizedFile); // Encodes image as a JPEG data stream JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out); JPEGEncodeParam param = encoder.getDefaultJPEGEncodeParam(bufferedImage); param.setQuality(quality, true); encoder.setJPEGEncodeParam(param); encoder.encode(bufferedImage); }
From source file:GifEncoder.java
/** Constructs a new GifEncoder using an 8-bit AWT Image. The image is assumed to be fully loaded. */ public GifEncoder(Image img) { width = img.getWidth(null); height = img.getHeight(null);/*from w w w . j a v a 2 s . co m*/ pixels = new byte[width * height]; PixelGrabber pg = new PixelGrabber(img, 0, 0, width, height, false); try { pg.grabPixels(); } catch (InterruptedException e) { System.err.println(e); } ColorModel cm = pg.getColorModel(); if (cm instanceof IndexColorModel) { pixels = (byte[]) (pg.getPixels()); // hpm IndexColorModel icm = (IndexColorModel) cm; setTransparentPixel(icm.getTransparentPixel()); } else throw new IllegalArgumentException("IMAGE_ERROR"); IndexColorModel m = (IndexColorModel) cm; int mapSize = m.getMapSize(); r = new byte[mapSize]; g = new byte[mapSize]; b = new byte[mapSize]; m.getReds(r); m.getGreens(g); m.getBlues(b); interlace = false; pixelIndex = 0; numPixels = width * height; }
From source file:pl.datamatica.traccar.api.providers.ImageProvider.java
public byte[] getMarker(String name) throws IOException { if (!markerCache.containsKey(name)) { Image icon = getImage(name + ".png"); if (icon == null) return null; float l = 30f / 141, t = 28f / 189, r = 110f / 141, b = 108f / 189; int w = emptyMarker.getWidth(null), h = emptyMarker.getHeight(null); int tw = (int) Math.round((r - l) * w), th = (int) Math.round((b - t) * h); //https://stackoverflow.com/a/7951324 int wi = icon.getWidth(null), hi = icon.getHeight(null); while (wi >= 2 * tw || hi >= 2 * th) { if (wi >= 2 * tw) wi /= 2;//from w w w .ja v a2 s .co m if (hi >= 2 * th) hi /= 2; BufferedImage tmp = new BufferedImage(wi, hi, BufferedImage.TYPE_INT_ARGB); Graphics2D g2 = tmp.createGraphics(); g2.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR); g2.drawImage(icon, 0, 0, wi, hi, null); g2.dispose(); icon = tmp; } BufferedImage marker = new BufferedImage(w, h, BufferedImage.TYPE_INT_ARGB); Graphics2D g = marker.createGraphics(); g.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR); g.drawImage(emptyMarker, 0, 0, null); g.drawImage(icon, (int) Math.round(l * w), (int) Math.round(t * h), tw, th, null); g.dispose(); ByteArrayOutputStream boss = new ByteArrayOutputStream(); ImageIO.write((RenderedImage) marker, "png", boss); markerCache.put(name, boss.toByteArray()); } return markerCache.get(name); }
From source file:org.sbs.util.ImageCompress.java
public String compressPic() { try {/*ww w.j a v a 2 s. c om*/ // ? file = new File(inputDir + inputFileName); if (!file.exists()) { return ""; } Image img = ImageIO.read(file); // ?? if (img.getWidth(null) == -1) { System.out.println(" can't read,retry!" + "<BR>"); return "no"; } else { int newWidth; int newHeight; // ? if (this.proportion == true) { // ? double rate1 = ((double) img.getWidth(null)) / (double) outputWidth + 0.1; double rate2 = ((double) img.getHeight(null)) / (double) outputHeight + 0.1; // ? double rate = rate1 > rate2 ? rate1 : rate2; newWidth = (int) (((double) img.getWidth(null)) / rate); newHeight = (int) (((double) img.getHeight(null)) / rate); } else { newWidth = outputWidth; // newHeight = outputHeight; // } BufferedImage tag = new BufferedImage((int) newWidth, (int) newHeight, BufferedImage.TYPE_INT_RGB); /* * Image.SCALE_SMOOTH ? ?? */ tag.getGraphics().drawImage(img.getScaledInstance(newWidth, newHeight, Image.SCALE_SMOOTH), 0, 0, null); FileOutputStream out = new FileOutputStream(outputDir + outputFileName); // JPEGImageEncoder?? JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out); encoder.encode(tag); out.close(); } } catch (IOException ex) { ex.printStackTrace(); } return "ok"; }
From source file:com.openbravo.pos.util.ThumbNailBuilder.java
private Image createThumbNail(Image img) { // MaskFilter filter = new MaskFilter(Color.WHITE); // ImageProducer prod = new FilteredImageSource(img.getSource(), filter); // img = Toolkit.getDefaultToolkit().createImage(prod); int targetw;//from w w w . j av a 2s . co m int targeth; double scalex = (double) m_width / (double) img.getWidth(null); double scaley = (double) m_height / (double) img.getHeight(null); if (scalex < scaley) { targetw = m_width; targeth = (int) (img.getHeight(null) * scalex); } else { targetw = (int) (img.getWidth(null) * scaley); targeth = (int) m_height; } int midw = img.getWidth(null); int midh = img.getHeight(null); BufferedImage midimg = null; Graphics2D g2d = null; Image previmg = img; int prevw = img.getWidth(null); int prevh = img.getHeight(null); do { if (midw > targetw) { midw /= 2; if (midw < targetw) { midw = targetw; } } else { midw = targetw; } if (midh > targeth) { midh /= 2; if (midh < targeth) { midh = targeth; } } else { midh = targeth; } if (midimg == null) { midimg = new BufferedImage(midw, midh, BufferedImage.TYPE_INT_ARGB); g2d = midimg.createGraphics(); g2d.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR); } g2d.drawImage(previmg, 0, 0, midw, midh, 0, 0, prevw, prevh, null); prevw = midw; prevh = midh; previmg = midimg; } while (midw != targetw || midh != targeth); g2d.dispose(); if (m_width != midimg.getWidth() || m_height != midimg.getHeight()) { midimg = new BufferedImage(m_width, m_height, BufferedImage.TYPE_INT_ARGB); int x = (m_width > targetw) ? (m_width - targetw) / 2 : 0; int y = (m_height > targeth) ? (m_height - targeth) / 2 : 0; g2d = midimg.createGraphics(); g2d.drawImage(previmg, x, y, x + targetw, y + targeth, 0, 0, targetw, targeth, null); g2d.dispose(); previmg = midimg; } return previmg; }
From source file:com.celements.photo.image.GenerateThumbnail.java
BufferedImage convertImageToBufferedImage(Image thumbImg, String watermark, String copyright, Color defaultBg) { BufferedImage thumb = new BufferedImage(thumbImg.getWidth(null), thumbImg.getHeight(null), BufferedImage.TYPE_INT_ARGB); Graphics2D g2d = thumb.createGraphics(); if (defaultBg != null) { g2d.setColor(defaultBg);/* w ww . j av a2s . c o m*/ g2d.fillRect(0, 0, thumbImg.getWidth(null), thumbImg.getHeight(null)); } g2d.drawImage(thumbImg, 0, 0, null); if ((watermark != null) && (!watermark.equals(""))) { drawWatermark(watermark, g2d, thumb.getWidth(), thumb.getHeight()); } if ((copyright != null) && (!copyright.equals(""))) { drawCopyright(copyright, g2d, thumb.getWidth(), thumb.getHeight()); } mLogger.info("thumbDimensions: " + thumb.getHeight() + "x" + thumb.getWidth()); return thumb; }
From source file:com.xpn.xwiki.plugin.image.ImagePlugin.java
/** * Reduces the size (i.e. the number of bytes) of an image by scaling its width and height and by reducing its * compression quality. This helps decreasing the time needed to download the image attachment. * /*from ww w . jav a 2 s . c o m*/ * @param attachment the image to be shrunk * @param requestedWidth the desired image width; this value is taken into account only if it is greater than zero * and less than the current image width * @param requestedHeight the desired image height; this value is taken into account only if it is greater than zero * and less than the current image height * @param keepAspectRatio {@code true} to preserve the image aspect ratio even when both requested dimensions are * properly specified (in this case the image will be resized to best fit the rectangle with the * requested width and height), {@code false} otherwise * @param requestedQuality the desired compression quality * @param context the XWiki context * @return the modified image attachment * @throws Exception if shrinking the image fails */ private XWikiAttachment shrinkImage(XWikiAttachment attachment, int requestedWidth, int requestedHeight, boolean keepAspectRatio, float requestedQuality, XWikiContext context) throws Exception { Image image = this.imageProcessor.readImage(attachment.getContentInputStream(context)); // Compute the new image dimension. int currentWidth = image.getWidth(null); int currentHeight = image.getHeight(null); int[] dimensions = reduceImageDimensions(currentWidth, currentHeight, requestedWidth, requestedHeight, keepAspectRatio); float quality = requestedQuality; if (quality < 0) { // If no scaling is needed and the quality parameter is not specified, return the original image. if (dimensions[0] == currentWidth && dimensions[1] == currentHeight) { return attachment; } quality = this.defaultQuality; } // Scale the image to the new dimensions. RenderedImage shrunkImage = this.imageProcessor.scaleImage(image, dimensions[0], dimensions[1]); // Write the shrunk image to a byte array output stream. ByteArrayOutputStream bout = new ByteArrayOutputStream(); this.imageProcessor.writeImage(shrunkImage, attachment.getMimeType(context), quality, bout); // Create an image attachment for the shrunk image. XWikiAttachment thumbnail = (XWikiAttachment) attachment.clone(); thumbnail.setContent(new ByteArrayInputStream(bout.toByteArray()), bout.size()); return thumbnail; }
From source file:Package.Projectoverviewservlet.java
@Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { frame.setAlwaysOnTop(true);//from w w w . j a va2 s . c o m if (request.getParameter("submit") != null) { Database database = null; try { database = new Database(); database.Connect(); } catch (SQLException | ClassNotFoundException ex) { Logger.getLogger(Projectoverviewservlet.class.getName()).log(Level.SEVERE, null, ex); } try { String contentType = request.getContentType(); if ((contentType.indexOf("multipart/form-data") >= 0)) { try { Part filePart = request.getPart("fileupload"); Image image = ImageIO.read(filePart.getInputStream()); String INSERT_PICTURE = "INSERT INTO \"PICTURE\"(\"PICTUREID\", \"PROJECTID\", \"HEIGHT\", \"WIDTH\", \"COLORTYPE\", \"PICTURE\") VALUES (PictureSequence.nextval, 1," + image.getHeight(null) + "," + image.getWidth(null) + ", 'Color', ?)"; InputStream is = null; PreparedStatement ps = null; try { is = filePart.getInputStream(); ps = database.myConn.prepareStatement(INSERT_PICTURE); ps.setBlob(1, is); ps.executeUpdate(); database.myConn.commit(); JOptionPane.showMessageDialog(frame, "De afbeelding is succesvol geupload."); } finally { try { ps.close(); is.close(); } catch (Exception exception) { } } } catch (IOException | ServletException | SQLException ex) { System.out.println(ex); } } else { JOptionPane.showMessageDialog(frame, "Er is iets fout gegaan probeer het opnieuw"); } } catch (Exception ex) { JOptionPane.showMessageDialog(frame, ex.getMessage()); } response.sendRedirect("projectoverview.jsp"); } if (request.getParameter("deleteproject") != null) { String[] selectresults = request.getParameterValues("selectproject"); po.deleteProject(Integer.parseInt(selectresults[0])); } if (request.getParameter("openproject") != null) { try { String[] selectresults = request.getParameterValues("selectproject"); Project project = po.getProject(Integer.parseInt(selectresults[0])); request.setAttribute("project", project); request.getRequestDispatcher("projectoverview.jsp").forward(request, response); } catch (Exception ex) { JOptionPane.showMessageDialog(frame, ex.getMessage()); } } if (request.getParameter("Save") != null) { Project project = (Project) request.getAttribute("project"); if (project != null) { try { System.out.println(request.getParameter("startdate")); po.updateProject(project.getProjectID(), request.getParameter("name"), request.getParameter("client"), new SimpleDateFormat("yyyy-MM-dd").parse(request.getParameter("startdate")), new SimpleDateFormat("yyyy-MM-dd").parse(request.getParameter("enddate"))); } catch (Exception ex) { } } else { String username = ""; for (Cookie cookie : request.getCookies()) { if (cookie.getName().equals("Email")) { username = cookie.getValue(); } } if (!username.isEmpty()) { try { po.createProject(po.connection.getCompanyID(username), request.getParameter("name"), request.getParameter("client"), new SimpleDateFormat("yyyy-MM-dd").parse(request.getParameter("startdate")), new SimpleDateFormat("yyyy-MM-dd").parse(request.getParameter("enddate"))); } catch (ParseException ex) { Logger.getLogger(Projectoverviewservlet.class.getName()).log(Level.SEVERE, null, ex); } } //roep create aan } request.getRequestDispatcher("projectoverview.jsp").forward(request, response); } if (request.getParameter("deleteimage") != null) { } if (request.getParameter("importimage") != null) { } if (request.getParameter("koppel") != null) { } if (request.getParameter("addemail") != null) { } if (request.getParameter("deleteemail") != null) { } if (request.getParameter("importemail") != null) { } }
From source file:info.magnolia.cms.taglibs.util.TextToImageTag.java
/** * Create an image file that is a scaled version of the original image * @param the original BufferedImage// ww w . j a v a2 s.c o m * @param the scale factor * @return the new BufferedImage */ private BufferedImage scaleImage(BufferedImage oriImgBuff, double scaleFactor) { // get the dimesnions of the original image int oriWidth = oriImgBuff.getWidth(); int oriHeight = oriImgBuff.getHeight(); // get the width and height of the new image int newWidth = new Double(oriWidth * scaleFactor).intValue(); int newHeight = new Double(oriHeight * scaleFactor).intValue(); // create the thumbnail as a buffered image Image newImg = oriImgBuff.getScaledInstance(newWidth, newHeight, Image.SCALE_AREA_AVERAGING); BufferedImage newImgBuff = new BufferedImage(newImg.getWidth(null), newImg.getHeight(null), BufferedImage.TYPE_INT_RGB); Graphics2D g = newImgBuff.createGraphics(); g.drawImage(newImg, 0, 0, null); g.dispose(); // return the newImgBuff return newImgBuff; }
From source file:org.sbs.util.ImageCompress.java
/** * @param originalFile//from www .jav a2s. co m * ? * @param resizedFile * ?? * @param width * ? * @param height * ? -1? * @param format * ? jpg, png, gif(?) * @throws IOException */ public void resize(File originalFile, File resizedFile, int width, int height, String format) throws IOException { if (format != null && "gif".equals(format.toLowerCase())) { resize(originalFile, resizedFile, width, height, 1); return; } FileInputStream fis = new FileInputStream(originalFile); ByteArrayOutputStream byteStream = new ByteArrayOutputStream(); int readLength = -1; int bufferSize = 1024; byte bytes[] = new byte[bufferSize]; while ((readLength = fis.read(bytes, 0, bufferSize)) != -1) { byteStream.write(bytes, 0, readLength); } byte[] in = byteStream.toByteArray(); fis.close(); byteStream.close(); Image inputImage = Toolkit.getDefaultToolkit().createImage(in); waitForImage(inputImage); int imageWidth = inputImage.getWidth(null); if (imageWidth < 1) throw new IllegalArgumentException("image width " + imageWidth + " is out of range"); int imageHeight = inputImage.getHeight(null); if (imageHeight < 1) throw new IllegalArgumentException("image height " + imageHeight + " is out of range"); // Create output image. if (height == -1) { double scaleW = (double) imageWidth / (double) width; double scaleY = (double) imageHeight / (double) height; if (scaleW >= 0 && scaleY >= 0) { if (scaleW > scaleY) { height = -1; } else { width = -1; } } } Image outputImage = inputImage.getScaledInstance(width, height, java.awt.Image.SCALE_DEFAULT); checkImage(outputImage); encode(new FileOutputStream(resizedFile), outputImage, format); }