List of usage examples for java.awt Image SCALE_SMOOTH
int SCALE_SMOOTH
To view the source code for java.awt Image SCALE_SMOOTH.
Click Source Link
From source file:com.xmage.launcher.XMageLauncher.java
private XMageLauncher() { locale = Locale.getDefault(); //locale = new Locale("it", "IT"); messages = ResourceBundle.getBundle("MessagesBundle", locale); localize();/* w w w . j a v a2 s.c o m*/ serverConsole = new XMageConsole("XMage Server console"); clientConsole = new XMageConsole("XMage Client console"); frame = new JFrame(messages.getString("frameTitle") + " " + Config.getVersion()); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setPreferredSize(new Dimension(800, 500)); frame.setResizable(false); createToolbar(); ImageIcon icon = new ImageIcon(XMageLauncher.class.getResource("/icon-mage-flashed.png")); frame.setIconImage(icon.getImage()); Random r = new Random(); int imageNum = 1 + r.nextInt(17); ImageIcon background = new ImageIcon(new ImageIcon( XMageLauncher.class.getResource("/backgrounds/" + Integer.toString(imageNum) + ".jpg")).getImage() .getScaledInstance(800, 480, Image.SCALE_SMOOTH)); mainPanel = new JLabel(background) { @Override public Dimension getPreferredSize() { Dimension size = super.getPreferredSize(); Dimension lmPrefSize = getLayout().preferredLayoutSize(this); size.width = Math.max(size.width, lmPrefSize.width); size.height = Math.max(size.height, lmPrefSize.height); return size; } }; mainPanel.addMouseListener(new MouseAdapter() { @Override public void mousePressed(MouseEvent e) { grabPoint = e.getPoint(); mainPanel.getComponentAt(grabPoint); } }); mainPanel.addMouseMotionListener(new MouseMotionAdapter() { @Override public void mouseDragged(MouseEvent e) { // get location of Window int thisX = frame.getLocation().x; int thisY = frame.getLocation().y; // Determine how much the mouse moved since the initial click int xMoved = (thisX + e.getX()) - (thisX + grabPoint.x); int yMoved = (thisY + e.getY()) - (thisY + grabPoint.y); // Move window to this position int X = thisX + xMoved; int Y = thisY + yMoved; frame.setLocation(X, Y); } }); mainPanel.setLayout(new GridBagLayout()); GridBagConstraints constraints = new GridBagConstraints(); constraints.insets = new Insets(10, 10, 10, 10); Font font16 = new Font("Arial", Font.BOLD, 16); Font font12 = new Font("Arial", Font.PLAIN, 12); Font font12b = new Font("Arial", Font.BOLD, 12); mainPanel.add(Box.createRigidArea(new Dimension(250, 50))); ImageIcon logo = new ImageIcon(new ImageIcon(XMageLauncher.class.getResource("/label-xmage.png")).getImage() .getScaledInstance(150, 75, Image.SCALE_SMOOTH)); xmageLogo = new JLabel(logo); constraints.gridx = 3; constraints.gridy = 0; constraints.gridheight = 1; constraints.gridwidth = GridBagConstraints.REMAINDER; constraints.anchor = GridBagConstraints.EAST; mainPanel.add(xmageLogo, constraints); textArea = new JTextArea(5, 40); textArea.setEditable(false); textArea.setForeground(Color.WHITE); textArea.setBackground(Color.BLACK); DefaultCaret caret = (DefaultCaret) textArea.getCaret(); caret.setUpdatePolicy(DefaultCaret.ALWAYS_UPDATE); scrollPane = new JScrollPane(textArea); scrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED); scrollPane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED); constraints.gridx = 2; constraints.gridy = 1; constraints.weightx = 1.0; constraints.weighty = 1.0; constraints.fill = GridBagConstraints.BOTH; mainPanel.add(scrollPane, constraints); labelProgress = new JLabel(messages.getString("progress")); labelProgress.setFont(font12); labelProgress.setForeground(Color.WHITE); constraints.gridy = 2; constraints.weightx = 0.0; constraints.weighty = 0.0; constraints.gridwidth = 1; constraints.anchor = GridBagConstraints.WEST; mainPanel.add(labelProgress, constraints); progressBar = new JProgressBar(0, 100); constraints.gridx = 3; constraints.weightx = 1.0; constraints.gridwidth = GridBagConstraints.REMAINDER; constraints.fill = GridBagConstraints.HORIZONTAL; mainPanel.add(progressBar, constraints); JPanel pnlButtons = new JPanel(); pnlButtons.setLayout(new GridBagLayout()); pnlButtons.setOpaque(false); constraints.gridx = 0; constraints.gridy = 3; constraints.gridheight = GridBagConstraints.REMAINDER; constraints.fill = GridBagConstraints.BOTH; mainPanel.add(pnlButtons, constraints); btnLaunchClient = new JButton(messages.getString("launchClient")); btnLaunchClient.setToolTipText(messages.getString("launchClient.tooltip")); btnLaunchClient.setFont(font16); btnLaunchClient.setForeground(Color.GRAY); btnLaunchClient.setEnabled(false); btnLaunchClient.setPreferredSize(new Dimension(180, 60)); btnLaunchClient.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { handleClient(); } }); constraints.gridx = GridBagConstraints.RELATIVE; constraints.gridy = 0; constraints.gridwidth = 1; constraints.fill = GridBagConstraints.BOTH; pnlButtons.add(btnLaunchClient, constraints); btnLaunchClientServer = new JButton(messages.getString("launchClientServer")); btnLaunchClientServer.setToolTipText(messages.getString("launchClientServer.tooltip")); btnLaunchClientServer.setFont(font12b); btnLaunchClientServer.setEnabled(false); btnLaunchClientServer.setForeground(Color.GRAY); btnLaunchClientServer.setPreferredSize(new Dimension(80, 40)); btnLaunchClientServer.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { handleServer(); handleClient(); } }); constraints.fill = GridBagConstraints.HORIZONTAL; pnlButtons.add(btnLaunchClientServer, constraints); btnLaunchServer = new JButton(messages.getString("launchServer")); btnLaunchServer.setToolTipText(messages.getString("launchServer.tooltip")); btnLaunchServer.setFont(font12b); btnLaunchServer.setEnabled(false); btnLaunchServer.setForeground(Color.GRAY); btnLaunchServer.setPreferredSize(new Dimension(80, 40)); btnLaunchServer.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { handleServer(); } }); pnlButtons.add(btnLaunchServer, constraints); btnUpdate = new JButton(messages.getString("update.xmage")); btnUpdate.setToolTipText(messages.getString("update.xmage.tooltip")); btnUpdate.setFont(font12b); btnUpdate.setForeground(Color.BLACK); btnUpdate.setPreferredSize(new Dimension(80, 40)); btnUpdate.setEnabled(true); btnUpdate.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { handleUpdate(); } }); pnlButtons.add(btnUpdate, constraints); btnCheck = new JButton(messages.getString("check.xmage")); btnCheck.setToolTipText(messages.getString("check.xmage.tooltip")); btnCheck.setFont(font12b); btnCheck.setForeground(Color.BLACK); btnCheck.setPreferredSize(new Dimension(80, 40)); btnCheck.setEnabled(true); btnCheck.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { handleCheckUpdates(); } }); pnlButtons.add(btnCheck, constraints); frame.add(mainPanel); frame.pack(); Dimension dim = Toolkit.getDefaultToolkit().getScreenSize(); frame.setLocation(dim.width / 2 - frame.getSize().width / 2, dim.height / 2 - frame.getSize().height / 2); }
From source file:com.lingxiang2014.util.ImageUtils.java
public static void zoom(File srcFile, File destFile, int destWidth, int destHeight) { Assert.notNull(srcFile);//w ww . j a v a 2s . c om 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.shending.support.CompressPic.java
public String compressPic() { try {//from ww w .j a v a 2s . c o m // ? file = new File(inputDir); //System.out.println(inputDir + inputFileName); if (!file.exists()) { //throw new Exception("?"); } 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); File f = new File(outputDir); if (!f.exists()) { f.mkdirs(); } 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:net.sf.webphotos.tools.Thumbnail.java
/** * Cria thumbs para as imagens. Testa se j existem valores setados para o * thumb, se no existir chama o mtodo/*from ww w.j a va 2s.c om*/ * {@link net.sf.webphotos.Thumbnail#inicializar() inicializar} para setar * seus valores. Abre o arquivo de imagem passado como parmetro e checa se * uma foto vlida. Obtm o tamanho original da imagem, checa se est no * formato paisagem ou retrato e utiliza o mtodo * {@link java.awt.Image#getScaledInstance(int,int,int) getScaledInstance} * para calcular os thumbs. Ao final, salva as imagens. * * @param caminhoCompletoImagem Caminho da imagem. */ public static void makeThumbs(String caminhoCompletoImagem) { String diretorio, arquivo; if (t1 == 0) { inicializar(); } try { File f = new File(caminhoCompletoImagem); if (!f.isFile() || !f.canRead()) { Util.err.println("[Thumbnail.makeThumbs]/ERRO: Erro no caminho do arquivo " + caminhoCompletoImagem + " incorreto"); return; } // Foto em alta corrompida if (getFormatName(f) == null) { Util.err.println("[Thumbnail.makeThumbs]/ERRO: Foto Corrompida"); return; } else { Util.out.println("[Thumbnail.makeThumbs]/INFO: Foto Ok!"); } diretorio = f.getParent(); arquivo = f.getName(); ImageIcon ii = new ImageIcon(f.getCanonicalPath()); Image i = ii.getImage(); Image tumb1, tumb2, tumb3, tumb4; // obtm o tamanho da imagem original int iWidth = i.getWidth(null); int iHeight = i.getHeight(null); //int w, h; if (iWidth > iHeight) { tumb1 = i.getScaledInstance(t1, (t1 * iHeight) / iWidth, Image.SCALE_SMOOTH); tumb2 = i.getScaledInstance(t2, (t2 * iHeight) / iWidth, Image.SCALE_SMOOTH); tumb3 = i.getScaledInstance(t3, (t3 * iHeight) / iWidth, Image.SCALE_SMOOTH); tumb4 = i.getScaledInstance(t4, (t4 * iHeight) / iWidth, Image.SCALE_SMOOTH); //w = t4; //h = (t4 * iHeight) / iWidth; } else { tumb1 = i.getScaledInstance((t1 * iWidth) / iHeight, t1, Image.SCALE_SMOOTH); tumb2 = i.getScaledInstance((t2 * iWidth) / iHeight, t2, Image.SCALE_SMOOTH); tumb3 = i.getScaledInstance((t3 * iWidth) / iHeight, t3, Image.SCALE_SMOOTH); tumb4 = i.getScaledInstance((t4 * iWidth) / iHeight, t4, Image.SCALE_SMOOTH); //w = (t4 * iWidth) / iHeight; //h = t4; } tumb4 = estampar(tumb4); Util.log("Salvando Imagens"); save(tumb1, diretorio + File.separator + "_a" + arquivo); save(tumb2, diretorio + File.separator + "_b" + arquivo); save(tumb3, diretorio + File.separator + "_c" + arquivo); save(tumb4, diretorio + File.separator + "_d" + arquivo); } catch (Exception e) { Util.err.println("[Thumbnail.makeThumbs]/ERRO: Inesperado - " + e.getMessage()); e.printStackTrace(Util.err); } }
From source file:common.utils.ImageUtils.java
/** * resize input image to new dinesions(only smaller) and save it to file * @param image input image for scaling * @param scale_factor factor for scaling image * @param rez writes resulting image to a file * @throws IOException/* ww w . ja v a 2 s . co m*/ */ public static void saveScaledImageWidth(BufferedImage image, double scale_factor, OutputStream rez) throws IOException { //long time_resize = System.currentTimeMillis(); if (scale_factor == 1) { writeImage(image, 1, rez); } else { int width = (int) (scale_factor * image.getWidth()); int height = (int) (scale_factor * image.getHeight()); //BufferedImage scaled_bi = new BufferedImage( image.getWidth(), image.getHeight(), image.getType() ); int type = image.getType(); BufferedImage scaled_bi; if (type == BufferedImage.TYPE_CUSTOM) { scaled_bi = new BufferedImage(width, height, BufferedImage.TYPE_3BYTE_BGR); } else { scaled_bi = new BufferedImage(width, height, type); } Graphics2D g2 = scaled_bi.createGraphics(); //g2.drawImage(image, at, null); g2.drawImage(image.getScaledInstance(width, height, Image.SCALE_SMOOTH), 0, 0, null); writeImage(scaled_bi, 1, rez); g2.dispose(); } //time_resize = System.currentTimeMillis() - time_resize; //System.out.print("time_resize=" + (time_resize) + "; "); }
From source file:de.anycook.upload.UploadHandler.java
/** * speichert eine kleine Version des Bildes * * @param image BufferedImage/*from w w w. j av a 2 s .co m*/ * @param filename Name der zu erzeugenden Datei */ private void saveSmallImage(BufferedImage image, String filename) throws IOException { int height = image.getHeight(); int width = image.getWidth(); double imageRatio = (double) width / (double) height; int xtranslate = 0; int ytranslate = 0; if (imageRatio > 1) { xtranslate = (width - height) / 2; } else { ytranslate = (height - width) / 2; } BufferedImage tempImage = image.getSubimage(xtranslate, ytranslate, width - xtranslate * 2, height - ytranslate * 2); BufferedImage newImage = new BufferedImage(smallSize, smallSize, BufferedImage.TYPE_INT_RGB); newImage.getGraphics().drawImage(tempImage.getScaledInstance(smallSize, smallSize, Image.SCALE_SMOOTH), 0, 0, null); imageSaver.save("small/", filename, newImage); }
From source file:bayesGame.ui.transformers.BayesNodeProbabilityToGridTransformer.java
@Override public Icon transform(BayesNode node) { Fraction probability = node.getProbability(); double cells = probability.percentageValue(); Image grid;//from ww w . ja v a 2 s. co m Color trueColor = BayesGame.trueColor; Color falseColor = BayesGame.falseColor; boolean hiddennode = node.hasProperty("hidden"); boolean targetnode = node.hasProperty("target"); if (node.hasProperty("misguessed")) { trueColor = Color.GRAY; falseColor = Color.BLACK; } // TODO: indicate target nodes somehow if (node.cptName == null) { node.cptName = ""; } if (node.cptName.equals("DetIS")) { grid = new IsNodePainter().paintPercentage(cells, trueColor, falseColor, rows, columns, squaresize); } else if (node.cptName.equals("DetNOT")) { grid = new NotNodePainter().paintPercentage(cells, trueColor, falseColor, rows, columns, squaresize); } else if (node.cptName.equals("Prior")) { grid = PriorPainter.paintPercentage(cells, trueColor, falseColor, rows, columns, squaresize); } else if (node.cptName.equals("DetOR")) { List<Object> parentTypeList = net.getParents(node.type); Fraction parentNode1Probability = net.getProbability(parentTypeList.get(0)); Fraction parentNode2Probability = net.getProbability(parentTypeList.get(1)); grid = OrNodePainter.paintPercentage(trueColor, falseColor, (int) (rows * squaresize * 3.5), squaresize, node, parentNode1Probability, parentNode2Probability); } else if (node.cptName.equals("DetAND")) { List<Object> parentTypeList = net.getParents(node.type); Fraction parentNode1Probability = net.getProbability(parentTypeList.get(0)); Fraction parentNode2Probability = net.getProbability(parentTypeList.get(1)); grid = AndNodePainter.paintPercentage(trueColor, falseColor, (int) (rows * squaresize * 3.5), squaresize, node, parentNode1Probability, parentNode2Probability); } else if (node.cptName.equals("DetNOTAnd")) { grid = DetNOTAnd.paintPercentage(cells, trueColor, falseColor, rows, columns, squaresize, node); } else if (node.cptName.equals("Bayes")) { List<Object> parentTypeList = net.getParents(node.type); Fraction parentNodeProbability = net.getProbability(parentTypeList.get(0)); grid = BayesPainter.paintPercentage(cells, trueColor, falseColor, rows, columns, squaresize, node, parentNodeProbability); } else { grid = GridPainter.paintPercentage(cells, trueColor, falseColor, rows, columns, squaresize); } if (hiddennode) { grid = NodePainter.getBorders((BufferedImage) grid, Color.BLACK); } else if (!node.isObserved()) { grid = NodePainter.getBorders((BufferedImage) grid, Color.GRAY); } int x_size = grid.getHeight(null); double size_multiplier = 0.7; int new_x_size = (int) (x_size * size_multiplier); ImageIcon icon = new ImageIcon(grid.getScaledInstance(-1, new_x_size, Image.SCALE_SMOOTH)); // ImageIcon icon = new ImageIcon(grid); return icon; }
From source file:com.github.cmisbox.ui.BaseFrame.java
public Image getImage(String resource, Integer height, Integer width) { try {/*from w ww. j a v a 2 s . com*/ BufferedImage image = ImageIO.read(this.getClass().getResource(resource)); if ((height != null) && (width != null) && ((image.getHeight() != height) || (image.getWidth() != width))) { return image.getScaledInstance(width, height, Image.SCALE_SMOOTH); } return image; } catch (IOException e1) { this.log.error(e1); } return null; }
From source file:net.groupbuy.util.ImageUtils.java
/** * /* w ww .j a v a 2s. com*/ * * @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
/** * //w w w. java 2s . 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); } } } }