List of usage examples for javax.imageio ImageIO read
public static BufferedImage read(ImageInputStream stream) throws IOException
From source file:com.pdfhow.diff.UploadServlet.java
/** * Handles the HTTP <code>GET</code> method. * * @param request//ww w. j a v a 2s . c o m * servlet request * @param response * servlet response * @throws ServletException * if a servlet-specific error occurs * @throws IOException * if an I/O error occurs */ @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { if (request.getParameter("getfile") != null && !request.getParameter("getfile").isEmpty()) { File file = new File( request.getServletContext().getRealPath("/") + "imgs/" + request.getParameter("getfile")); if (file.exists()) { int bytes = 0; ServletOutputStream op = response.getOutputStream(); response.setContentType(getMimeType(file)); response.setContentLength((int) file.length()); response.setHeader("Content-Disposition", "inline; filename=\"" + file.getName() + "\""); byte[] bbuf = new byte[1024]; DataInputStream in = new DataInputStream(new FileInputStream(file)); while ((in != null) && ((bytes = in.read(bbuf)) != -1)) { op.write(bbuf, 0, bytes); } in.close(); op.flush(); op.close(); } } else if (request.getParameter("delfile") != null && !request.getParameter("delfile").isEmpty()) { File file = new File( request.getServletContext().getRealPath("/") + "imgs/" + request.getParameter("delfile")); if (file.exists()) { file.delete(); // TODO:check and report success } } else if (request.getParameter("getthumb") != null && !request.getParameter("getthumb").isEmpty()) { File file = new File( request.getServletContext().getRealPath("/") + "imgs/" + request.getParameter("getthumb")); if (file.exists()) { System.out.println(file.getAbsolutePath()); String mimetype = getMimeType(file); if (mimetype.endsWith("png") || mimetype.endsWith("jpeg") || mimetype.endsWith("jpg") || mimetype.endsWith("gif")) { BufferedImage im = ImageIO.read(file); if (im != null) { BufferedImage thumb = Scalr.resize(im, 75); ByteArrayOutputStream os = new ByteArrayOutputStream(); if (mimetype.endsWith("png")) { ImageIO.write(thumb, "PNG", os); response.setContentType("image/png"); } else if (mimetype.endsWith("jpeg")) { ImageIO.write(thumb, "jpg", os); response.setContentType("image/jpeg"); } else if (mimetype.endsWith("jpg")) { ImageIO.write(thumb, "jpg", os); response.setContentType("image/jpeg"); } else { ImageIO.write(thumb, "GIF", os); response.setContentType("image/gif"); } ServletOutputStream srvos = response.getOutputStream(); response.setContentLength(os.size()); response.setHeader("Content-Disposition", "inline; filename=\"" + file.getName() + "\""); os.writeTo(srvos); srvos.flush(); srvos.close(); } } } // TODO: check and report success } else { PrintWriter writer = response.getWriter(); writer.write("call POST with multipart form data"); } }
From source file:de.kp.ames.web.function.dms.DmsDQM.java
/** * @param item/*from ww w . j ava 2 s .co m*/ * @return * @throws Exception */ public ImageUtil getImage(String item) throws Exception { ImageCacheManager cacheManager = ImageCacheManager.getInstance(); DmsImage cacheEntry = (DmsImage) cacheManager.getFromCache(item); BufferedImage image = null; String fileName = null; String mimetype = null; if (cacheEntry == null) { ExtrinsicObjectImpl eo = (ExtrinsicObjectImpl) getRegistryObjectById(item); if (eo == null) throw new Exception("[DmsDQM] An image with id <" + item + "> does not exist."); mimetype = eo.getMimeType(); fileName = eo.getDisplayName(); if ((mimetype != null) && mimetype.startsWith("image")) { DataHandler handler = eo.getRepositoryItem(); image = ImageIO.read(handler.getInputStream()); ImageUtil imageUtil = new ImageUtil(GraphicsUtil.createSource(image), mimetype); imageUtil.setFileName(fileName); return imageUtil; } else { return null; } } else { image = cacheEntry.getImage(); mimetype = cacheEntry.getMimetype(); fileName = cacheEntry.getName(); ImageUtil imageUtil = new ImageUtil(GraphicsUtil.createSource(image), mimetype); imageUtil.setFileName(fileName); return imageUtil; } }
From source file:Data.java
/** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor./*w w w . j a va2 s . c om*/ * @throws ClassNotFoundException * @throws IOException * @throws SQLException */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code"> private void initComponents() throws ClassNotFoundException, IOException, SQLException { Connection dataFridge = getDbConnection(); Statement stmt = dataFridge.createStatement(); GridBagConstraints gridBagConstraints; panelPrincipal = new JPanel(); panelCenter = new JPanel(); panelHeader = new JPanel(); btnHome = new JButton(); dataList = new JComboBox(); btnOk = new JButton(); panelData = new JScrollPane(); panelRealTime = new JPanel(); tempRealTime = new JLabel(); humRealTime = new JLabel(); // Set unit temperature switch (param.tempUnitList.getSelectedIndex()) { case 0: tempUnit = "C"; break; case 1: tempUnit = "F"; break; default: break; } setPreferredSize(new Dimension(512, 400)); setLayout(null); panelPrincipal.setPreferredSize(new Dimension(512, 400)); panelPrincipal.setLayout(new BorderLayout()); panelHeader.setPreferredSize(new Dimension(512, 40)); panelHeader.setLayout(new GridBagLayout()); ClassLoader classLoader = Thread.currentThread().getContextClassLoader(); InputStream input = classLoader.getResourceAsStream("home.png"); Image iconeHome = ImageIO.read(input); btnHome.setIcon(new ImageIcon(iconeHome)); btnHome.setPreferredSize(new Dimension(40, 40)); gridBagConstraints = new GridBagConstraints(); gridBagConstraints.anchor = GridBagConstraints.LINE_START; gridBagConstraints.insets = new Insets(0, 0, 0, 50); panelHeader.add(btnHome, gridBagConstraints); dataList.setModel( new DefaultComboBoxModel(new String[] { "Donnes en temps rel", "Graphique des temperatures" })); dataList.setPreferredSize(new Dimension(250, 40)); gridBagConstraints = new GridBagConstraints(); gridBagConstraints.anchor = GridBagConstraints.LINE_END; gridBagConstraints.insets = new Insets(0, 0, 0, 10); panelHeader.add(dataList, gridBagConstraints); btnOk.setFont(new Font("Tahoma", 0, 10)); // NOI18N btnOk.setText("OK"); btnOk.setPreferredSize(new Dimension(60, 40)); btnOk.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent evt) { btnOKActionPerformed(evt); } }); gridBagConstraints = new GridBagConstraints(); gridBagConstraints.anchor = GridBagConstraints.LINE_START; gridBagConstraints.insets = new Insets(0, 5, 0, 70); panelHeader.add(btnOk, gridBagConstraints); panelPrincipal.add(panelHeader, BorderLayout.NORTH); panelCenter.setLayout(new BorderLayout()); JFreeChart chart = createChart(createDataset(stmt)); panelChart = new ChartPanel(chart); panelChart.setVisible(true); panelData = new JScrollPane(getTbleData(stmt)); tempRealTime.setFont(new java.awt.Font("Meiryo UI", 1, 18)); // NOI18N humRealTime.setFont(new java.awt.Font("Meiryo UI", 1, 18)); // NOI18N panelRealTime.setLayout(new GridBagLayout()); gridBagConstraints = new GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 0; gridBagConstraints.insets = new Insets(18, 0, 0, 0); gridBagConstraints.anchor = GridBagConstraints.LINE_START; panelRealTime.add(tempRealTime, gridBagConstraints); gridBagConstraints = new GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 1; gridBagConstraints.insets = new Insets(0, 0, 10, 0); gridBagConstraints.anchor = GridBagConstraints.LINE_START; panelRealTime.add(humRealTime, gridBagConstraints); panelCenter.add(panelRealTime, BorderLayout.NORTH); panelCenter.add(panelData, BorderLayout.CENTER); panelPrincipal.add(panelCenter, BorderLayout.CENTER); add(panelPrincipal); panelPrincipal.setBounds(0, 0, 512, 340); stmt.close(); dataFridge.close(); }
From source file:de.mprengemann.intellij.plugin.androidicons.util.ImageUtils.java
public static BufferedImage resizeNinePatchImage(ImageInformation information) throws IOException { BufferedImage image = ImageIO.read(information.getImageFile()); if (MathUtils.floatEquals(information.getFactor(), 1f)) { return image; }/* w w w. j a v a2 s . c om*/ BufferedImage trimmedImage = trim9PBorder(image); ImageInformation trimmedImageInformation = ImageInformation.newBuilder(information) .setExportName(getExportName("trimmed", information.getExportName())).build(); saveImageTempFile(trimmedImage, trimmedImageInformation); trimmedImage = resizeNormalImage(trimmedImage, trimmedImageInformation); saveImageTempFile(trimmedImage, ImageInformation.newBuilder(trimmedImageInformation) .setExportName(getExportName("trimmedResized", information.getExportName())).build()); BufferedImage borderImage; int w = trimmedImage.getWidth(); int h = trimmedImage.getHeight(); try { borderImage = generateBordersImage(image, w, h); } catch (Exception e) { return null; } int[] rgbArray = new int[w * h]; trimmedImage.getRGB(0, 0, w, h, rgbArray, 0, w); borderImage.setRGB(1, 1, w, h, rgbArray, 0, w); return borderImage; }
From source file:fr.mby.opa.picsimpl.service.BasicPictureFactory.java
protected void loadPicture(final Picture picture, final byte[] contents, final BufferedInputStream stream) throws IOException, UnsupportedPictureTypeException { // Load BufferedImage stream.reset();//ww w. j a va 2 s . c om final BufferedImage originalImage = ImageIO.read(stream); if (originalImage == null) { throw new UnsupportedPictureTypeException(picture.getFilename()); } final int width = originalImage.getWidth(); final int height = originalImage.getHeight(); picture.setWidth(width); picture.setHeight(height); picture.setSize(contents.length); // Load thumbnail this.loadThumbnail(picture, originalImage); // Search for picture format String format = null; // with Java image readers stream.reset(); final ImageInputStream imageStream = ImageIO.createImageInputStream(stream); final Iterator<ImageReader> imageReaders = ImageIO.getImageReaders(imageStream); if (imageReaders.hasNext()) { format = imageReaders.next().getFormatName(); } // In picture filename extension if (format == null) { format = FilenameUtils.getExtension(picture.getFilename()); } // Default format if (format == null) { format = BasicPictureFactory.DEFAULT_PICTURE_FORMAT; } picture.setFormat(format.toLowerCase()); // Build Contents final BinaryImage image = new BinaryImage(); image.setData(contents); image.setFilename(picture.getFilename()); image.setFormat(format); image.setWidth(width); image.setHeight(height); picture.setImage(image); }
From source file:br.com.cobranca.util.Util.java
/** * Metodo que gera Boleto/*from w ww.j a va2 s . co m*/ * * @param devedor * @param divida * @return */ public static String gerarBoleto(Devedor devedor, Divida divida) { ContasReceberDAO contasReceberDAO = new ContasReceberDAO(); String filePDF = ""; try { BancoCobranca bancoCobranca = new BancoCobranca(); Cedente cedente = new Cedente("Syscob", "43926785000130"); Banco banco = BancosSuportados.BANCOOB.create(); bancoCobranca.setAgencia(4321); bancoCobranca.setBancoNome("Sicoobcred-Acif"); bancoCobranca.setCarteira(01); bancoCobranca.setCc(200234); bancoCobranca.setCcDv(8); bancoCobranca.setCedenteCnpj("43926785000130"); bancoCobranca.setCedenteNome("Syscob"); bancoCobranca.setNossoNumero(00001); bancoCobranca.setNossoNumeroMaximo(99999); banco.setImgLogo(ImageIO.read(new File(FacesContext.getCurrentInstance().getExternalContext() .getRealPath("/resources/image/logo.jpg")))); //banco.setImgLogo(ImageIO.read(new File("P:\\Cobranca\\template\\logo.jpg"))); ContaBancaria contaBancariaCed = new ContaBancaria(banco); String conta = String.valueOf(200234); String dig = String.valueOf(4); String contaC = conta + dig; NumeroDaConta numeroConta = new NumeroDaConta(Integer.valueOf(contaC)); numeroConta.setDigitoDaConta(dig); contaBancariaCed.setNumeroDaConta(numeroConta); Carteira carteira = new Carteira(); carteira.setTipoCobranca(TipoDeCobranca.SEM_REGISTRO); carteira.setCodigo(1); contaBancariaCed.setCarteira(carteira); contaBancariaCed.setAgencia(new Agencia(bancoCobranca.getAgencia())); cedente.addContaBancaria(contaBancariaCed); Sacado sacado = new Sacado(devedor.getNome(), devedor.getCpf() == null ? devedor.getCpf() : devedor.getCpf()); Endereco enderecoSac = new Endereco(); enderecoSac.setLogradouro(devedor.getEndereco()); enderecoSac.setNumero(devedor.getNumero()); enderecoSac.setComplemento(devedor.getComplemento()); enderecoSac.setBairro(devedor.getBairro()); enderecoSac.setCep(new CEP("")); enderecoSac.setLocalidade(devedor.getCidade()); enderecoSac.setUF(UnidadeFederativa.valueOfSigla(devedor.getUf())); sacado.addEndereco(enderecoSac); Titulo titulo = new Titulo(contaBancariaCed, sacado, cedente); titulo.setNumeroDoDocumento(completarCom(String.valueOf(divida.getId()), 8, "0", "e")); titulo.setDigitoDoNossoNumero("7"); titulo.setNossoNumero(completarCom(String.valueOf(divida.getId()), 8, "0", "e")); //titulo.setValor(BigDecimal.valueOf(totalBoleto)); titulo.setValor(new BigDecimal(divida.getValorDivida())); titulo.setDataDoDocumento(new Date()); Date dataVenc = new Date(); Calendar calendar = Calendar.getInstance(); calendar.setTime(dataVenc); calendar.add(Calendar.DATE, 5); dataVenc = calendar.getTime(); titulo.setDataDoVencimento(dataVenc); titulo.setAceite(Titulo.Aceite.A); titulo.setTipoDeMoeda(TipoDeMoeda.REAL); ParametrosBancariosMap parametros = new ParametrosBancariosMap(); parametros.adicione("ModalidadeDeCobranca", 2); titulo.setParametrosBancarios(parametros); // alimento na divida Boleto boleto = new Boleto(titulo); boleto.setLocalPagamento(""); boleto.setInstrucao2("1 - No raceber aps o vencimento"); boleto.addTextosExtras("txtRsAgenciaCodigoCedente", "4321 / 2002344-8"); boleto.addTextosExtras("txtFcAgenciaCodigoCedente", "4321 / 2002344-8"); File templatePersonalizado = new File(FacesContext.getCurrentInstance().getExternalContext() .getRealPath("/resources/reportTemp/template.pdf")); BoletoViewer boletoViewer = new BoletoViewer(boleto, templatePersonalizado); boletoViewer.getPdfAsFile(FacesContext.getCurrentInstance().getExternalContext().getRealPath("/") + "\\resources\\boletos\\boleto.pdf"); filePDF = "/resources/boletos/boleto.pdf"; //Gero contas Receber if (contasReceberDAO.inserirContasReceber(divida.getId(), divida.getValorDivida(), titulo.getNossoNumero(), titulo.getDataDoVencimento()) > 0) { enviarEmail(divida, FacesContext.getCurrentInstance().getExternalContext().getRealPath("/") + "resources\\boletos\\boleto.pdf"); } else { filePDF = ""; } } catch (Exception e) { mostrarMensagemErro("Informao: ", e.getMessage()); } return filePDF; }
From source file:com.frostwire.gui.library.tags.MP4Parser.java
static BufferedImage getArtworkFromMP4(File file) { BufferedImage image = null;/*from www . j av a2 s. c o m*/ try { BoxParser parser = new PropertyBoxParserImpl() { @Override public Box parseBox(DataSource byteChannel, Container parent) throws IOException { Box box = super.parseBox(byteChannel, parent); if (box instanceof AbstractBox) { ((AbstractBox) box).parseDetails(); } return box; } }; IsoFile iso = new IsoFile(new FileDataSourceImpl(file), parser); try { AppleCoverBox data = (AppleCoverBox) Path.getPath(iso.getMovieBox(), "/moov/udta/meta/ilst/covr"); data.parseDetails(); if (data != null) { byte[] imageData = data.getCoverData(); if (data.getDataType() == 13) { // jpg image = imageFromData(imageData); } else if (data.getDataType() == 14) { // png try { image = ImageIO.read(new ByteArrayInputStream(imageData, 0, imageData.length)); } catch (IIOException e) { LOG.warn("Unable to decode png image from data tag"); } } } } finally { IOUtils.closeQuietly(iso); } } catch (Throwable e) { //LOG.error("Unable to read cover art from mp4 file: " + file); } return 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 ww w .j a va2s. 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:levelBuilder.DialogMaker.java
/** * First window to interact with. Offers options of load graph or new graph. *//* ww w . j a va 2s. c o m*/ private static void splashWindow() { final JFrame frame = new JFrame("Dialog Maker"); //Handles button pushes. class SplashActionHandler implements ActionListener { @Override public void actionPerformed(ActionEvent e) { frame.dispose(); if (e.getActionCommand().equals("loadGraph")) loadFilePopup(); else loadGraph(true); } } //Loads and sets background image. BufferedImage img = null; try { img = ImageIO.read(new File(imgDir + "splash.png")); } catch (IOException e) { e.printStackTrace(); } final BufferedImage img2 = img; JPanel panel = new JPanel() { @Override protected void paintComponent(Graphics g) { super.paintComponent(g); g.drawImage(img2, 0, 0, null); } }; panel.setOpaque(true); panel.setLayout(new BorderLayout()); panel.setPreferredSize(new Dimension(800, 600)); panel.setBorder(BorderFactory.createEmptyBorder(0, 0, 300, 0)); JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.CENTER)); buttonPanel.setOpaque(false); //Buttons JButton loadMap = new JButton("Load Graph"); loadMap.setActionCommand("loadGraph"); loadMap.addActionListener(new SplashActionHandler()); buttonPanel.add(loadMap); JButton newMap = new JButton("New Graph"); newMap.setActionCommand("newGraph"); newMap.addActionListener(new SplashActionHandler()); buttonPanel.add(newMap); panel.add(buttonPanel, BorderLayout.SOUTH); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.add(panel); frame.pack(); frame.setVisible(true); }
From source file:ch.rasc.downloadchart.DownloadChartServlet.java
private static void handleJpg(HttpServletResponse response, byte[] imageData, Integer width, Integer height, String filename, JpegOptions options) throws IOException { response.setContentType("image/jpeg"); response.setHeader("Content-Disposition", "attachment; filename=\"" + filename + ".jpg\";"); BufferedImage image = ImageIO.read(new ByteArrayInputStream(imageData)); Dimension newDimension = calculateDimension(image, width, height); int imgWidth = image.getWidth(); int imgHeight = image.getHeight(); if (newDimension != null) { imgWidth = newDimension.width;/*from w w w . ja v a 2 s . c o m*/ imgHeight = newDimension.height; } BufferedImage newImage = new BufferedImage(imgWidth, imgHeight, BufferedImage.TYPE_INT_RGB); Graphics2D g = newImage.createGraphics(); g.drawImage(image, 0, 0, imgWidth, imgHeight, Color.BLACK, null); g.dispose(); if (newDimension != null) { g.setComposite(AlphaComposite.Src); g.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR); g.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY); g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); } try (ImageOutputStream ios = ImageIO.createImageOutputStream(response.getOutputStream())) { Iterator<ImageWriter> iter = ImageIO.getImageWritersByFormatName("jpg"); ImageWriter writer = iter.next(); ImageWriteParam iwp = writer.getDefaultWriteParam(); iwp.setCompressionMode(ImageWriteParam.MODE_EXPLICIT); if (options != null && options.quality != null && options.quality != 0 && options.quality != 100) { iwp.setCompressionQuality(options.quality / 100f); } else { iwp.setCompressionQuality(1); } writer.setOutput(ios); writer.write(null, new IIOImage(newImage, null, null), iwp); writer.dispose(); } }