List of usage examples for java.awt Image getScaledInstance
public Image getScaledInstance(int width, int height, int hints)
From source file:se.trixon.almond.GraphicsHelper.java
public static Image scaleImage(Image image, Dimension dimension) { Image newImage;/*from w w w . j ava 2 s . co m*/ int height = image.getHeight(null); int width = image.getWidth(null); if (width > height) { newImage = image.getScaledInstance((int) dimension.getWidth(), (int) (dimension.getWidth() * height) / width, Image.SCALE_SMOOTH); } else { newImage = image.getScaledInstance((int) (dimension.getWidth() * width) / height, (int) dimension.getWidth(), Image.SCALE_SMOOTH); } return newImage; }
From source file:net.yacy.cora.util.Html2Image.java
/** * convert a pdf (first page) to an image. proper values are i.e. width = 1024, height = 1024, density = 300, quality = 75 * using internal pdf library or external command line tool on linux or mac * @param pdf input pdf file/*from w w w . j a va 2s. co m*/ * @param image output jpg file * @param width * @param height * @param density (dpi) * @param quality * @return */ public static boolean pdf2image(File pdf, File image, int width, int height, int density, int quality) { final File convert = convertMac1.exists() ? convertMac1 : convertMac2.exists() ? convertMac2 : convertDebian; // convert pdf to jpg using internal pdfbox capability if (OS.isWindows || !convert.exists()) { try { PDDocument pdoc = PDDocument.load(pdf); BufferedImage bi = new PDFRenderer(pdoc).renderImageWithDPI(0, density, ImageType.RGB); return ImageIO.write(bi, "jpg", image); } catch (IOException ex) { } } // convert on mac or linux using external command line utility try { // i.e. convert -density 300 -trim yacy.pdf[0] -trim -resize 1024x -crop x1024+0+0 -quality 75% yacy-convert-300.jpg // note: both -trim are necessary, otherwise it is trimmed only on one side. The [0] selects the first page of the pdf String command = convert.getAbsolutePath() + " -density " + density + " -trim " + pdf.getAbsolutePath() + "[0] -trim -resize " + width + "x -crop x" + height + "+0+0 -quality " + quality + "% " + image.getAbsolutePath(); List<String> message = OS.execSynchronous(command); if (image.exists()) return true; ConcurrentLog.warn("Html2Image", "failed to create image with command: " + command); for (String m : message) ConcurrentLog.warn("Html2Image", ">> " + m); // another try for mac: use Image Events using AppleScript in osacript commands... // the following command overwrites a pdf with an png, so we must make a copy first if (!OS.isMacArchitecture) return false; File pngFile = new File(pdf.getAbsolutePath() + ".tmp.pdf"); org.apache.commons.io.FileUtils.copyFile(pdf, pngFile); String[] commandx = { "osascript", "-e", "set ImgFile to \"" + pngFile.getAbsolutePath() + "\"", "-e", "tell application \"Image Events\"", "-e", "set Img to open file ImgFile", "-e", "save Img as PNG", "-e", "end tell" }; //ConcurrentLog.warn("Html2Image", "failed to create image with command: " + commandx); message = OS.execSynchronous(commandx); for (String m : message) ConcurrentLog.warn("Html2Image", ">> " + m); // now we must read and convert this file to a jpg with the target size 1024x1024 try { File newPngFile = new File(pngFile.getAbsolutePath() + ".png"); pngFile.renameTo(newPngFile); Image img = ImageParser.parse(pngFile.getAbsolutePath(), FileUtils.read(newPngFile)); final Image scaled = img.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) { } // finally write the image final BufferedImage bi = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB); bi.createGraphics().drawImage(scaled, 0, 0, width, height, null); ImageIO.write(bi, "jpg", image); newPngFile.delete(); return image.exists(); } catch (IOException e) { ConcurrentLog.logException(e); return false; } } catch (IOException e) { e.printStackTrace(); return false; } }
From source file:net.rptools.lib.image.ImageUtil.java
public static Image resizeImage(Image image, int w, int h) { // Default to 30x30 w/h not passed return image.getScaledInstance(w, h, Image.SCALE_SMOOTH); }
From source file:rega.genotype.ui.util.GenotypeLib.java
public static void scalePNG(File in, File out, double perc) throws IOException { Image i = ImageIO.read(in); Image resizedImage = null;// w w w .j ava 2s . c o m int newWidth = (int) (i.getWidth(null) * perc / 100.0); int newHeight = (int) (i.getHeight(null) * perc / 100.0); 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); ImageIO.write(bufferedImage, "png", out); }
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 w w w . j a v a2s. c o m*/ * {@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:org.mili.core.graphics.GraphicsUtil.java
/** * Scales an image./*ww w . jav a 2 s .com*/ * * @param i image. * @param scaleX scale to x >= 0. * @param scaleY scale to y >= 0. * @return scaled image. */ public static Image scaleImage(Image i, int scaleX, int scaleY) { Validate.notNull(i, "image cannot be null!"); Validate.isTrue(scaleX >= 0, "scaleX cannot be < 0!"); Validate.isTrue(scaleY >= 0, "scaleY cannot be < 0!"); if (scaleX == 0 && scaleY == 0) { return i; } double f = getRelationFactor(scaleX, scaleY, i); int x = (int) (i.getWidth(null) * f); int y = (int) (i.getHeight(null) * f); i = i.getScaledInstance(x, y, Image.SCALE_SMOOTH); ImageIcon ii = new ImageIcon(i); i = ii.getImage(); if (i instanceof ToolkitImage) { ToolkitImage ti = (ToolkitImage) i; i = ti.getBufferedImage(); } return i; }
From source file:generadorqr.jifrNuevoQr.java
public static void Mostrar_Visualizador(JLabel Pantalla, String RutaDestino) { try {/*ww w. java2s. c o m*/ Image capturarImgSoloLectura = ImageIO.read(new File(RutaDestino)); Image obtenerImagen = capturarImgSoloLectura.getScaledInstance(Pantalla.getPreferredSize().width, Pantalla.getPreferredSize().height, Image.SCALE_SMOOTH); Icon iconoEscalado = new ImageIcon(obtenerImagen); Pantalla.setIcon(iconoEscalado); } catch (java.io.IOException e) { e.printStackTrace(); } }
From source file:generadorqr.jifrGestionArticulos.java
public static void MostrarVisualizador(JLabel Pantalla, String RutaDestino) { try {// w w w. j ava 2 s . c o m Image capturarImgSoloLectura = ImageIO.read(new File(RutaDestino)); Image obtenerImagen = capturarImgSoloLectura.getScaledInstance(Pantalla.getPreferredSize().width, Pantalla.getPreferredSize().height - 10, Image.SCALE_SMOOTH); Icon iconoEscalado = new ImageIcon(obtenerImagen); Pantalla.setIcon(iconoEscalado); } catch (java.io.IOException e) { e.printStackTrace(); } }
From source file:Scale.java
public void go() { // Sleep first to see original rest();//from ww w.ja va2 s.c o m Image original = image; // Down fast image = original.getScaledInstance(200, -1, Image.SCALE_FAST); repaint(); rest(); // Down slow image = original.getScaledInstance(200, -1, Image.SCALE_SMOOTH); repaint(); rest(); // Up fast image = original.getScaledInstance(400, -1, Image.SCALE_FAST); repaint(); rest(); // Up slow image = original.getScaledInstance(400, -1, Image.SCALE_SMOOTH); repaint(); rest(); System.exit(0); }
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); }//ww 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); }