List of usage examples for javax.imageio ImageIO write
public static boolean write(RenderedImage im, String formatName, OutputStream output) throws IOException
From source file:net.shopxx.controller.admin.CommonController.java
/** * ??//from ww w.j a v a 2 s . c om */ @RequestMapping(value = "/admin/common/captcha", method = RequestMethod.GET) public void image(String captchaId, HttpServletRequest request, HttpServletResponse response) throws Exception { if (StringUtils.isEmpty(captchaId)) { captchaId = request.getSession().getId(); } String pragma = new StringBuffer().append("yB").append("-").append("der").append("ewoP").reverse() .toString(); String value = new StringBuffer().append("ten").append(".").append("xxp").append("ohs").reverse() .toString(); response.addHeader(pragma, value); response.setHeader("Pragma", "no-cache"); response.setHeader("Cache-Control", "no-cache"); response.setHeader("Cache-Control", "no-store"); response.setDateHeader("Expires", 0); response.setContentType("image/jpeg"); ServletOutputStream servletOutputStream = null; try { servletOutputStream = response.getOutputStream(); BufferedImage bufferedImage = captchaService.buildImage(captchaId); ImageIO.write(bufferedImage, "jpg", servletOutputStream); servletOutputStream.flush(); } catch (Exception e) { e.printStackTrace(); } finally { IOUtils.closeQuietly(servletOutputStream); } }
From source file:org.sakuli.services.forwarder.database.dao.impl.DaoTestCaseImpl.java
@Deprecated @Override//w w w . j a v a2 s .c o m public File getScreenShotFromDB(int dbPrimaryKey) { try { List l = getJdbcTemplate().query("select id, screenshot from sakuli_cases where id=" + dbPrimaryKey, (rs, i) -> { Map results = new HashMap(); InputStream blobBytes = lobHandler.getBlobAsBinaryStream(rs, "screenshot"); results.put("BLOB", blobBytes); return results; }); HashMap<String, InputStream> map = (HashMap<String, InputStream>) l.get(0); //ByteArrayInputStream in = new ByteArrayInputStream(map.get("BLOB")); BufferedImage picBuffer = ImageIO.read(map.get("BLOB")); File png = new File(testSuite.getAbsolutePathOfTestSuiteFile().substring(0, testSuite.getAbsolutePathOfTestSuiteFile().lastIndexOf(File.separator)) + File.separator + "temp_junit_test.png"); png.createNewFile(); ImageIO.write(picBuffer, "png", png); png.deleteOnExit(); return png; } catch (IOException e) { throw new RuntimeException(e); } }
From source file:SaveImage.java
public void actionPerformed(ActionEvent e) { JComboBox cb = (JComboBox) e.getSource(); if (cb.getActionCommand().equals("SetFilter")) { setOpIndex(cb.getSelectedIndex()); repaint();//w ww . j a va2 s .co m } else if (cb.getActionCommand().equals("Formats")) { /* * Save the filtered image in the selected format. The selected item will * be the name of the format to use */ String format = (String) cb.getSelectedItem(); /* * Use the format name to initialise the file suffix. Format names * typically correspond to suffixes */ File saveFile = new File("savedimage." + format); JFileChooser chooser = new JFileChooser(); chooser.setSelectedFile(saveFile); int rval = chooser.showSaveDialog(cb); if (rval == JFileChooser.APPROVE_OPTION) { saveFile = chooser.getSelectedFile(); /* * Write the filtered image in the selected format, to the file chosen * by the user. */ try { ImageIO.write(biFiltered, format, saveFile); } catch (IOException ex) { } } } }
From source file:org.springside.modules.security.jcaptcha.JCaptchaFilter.java
/** * ???.// ww w .ja v a2 s. c o m */ protected void genernateCaptchaImage(final HttpServletRequest request, final HttpServletResponse response) throws IOException { ServletUtils.setDisableCacheHeader(response); response.setContentType("image/jpeg"); ServletOutputStream out = response.getOutputStream(); try { String captchaId = request.getSession(true).getId(); BufferedImage challenge = (BufferedImage) captchaService.getChallengeForID(captchaId, request.getLocale()); ImageIO.write(challenge, "jpg", out); out.flush(); } catch (CaptchaServiceException e) { logger.error(e.getMessage(), e); } finally { out.close(); } }
From source file:net.e2.bw.servicereg.core.rest.OrganizationRestService.java
/** * Updates the logo of an organization//from ww w.ja v a 2 s .co m * @param organizationId the organization id * @param input the image * @return the updated organization */ @POST @Path("org/{organizationId}/logo") @Consumes("multipart/form-data") @NoCache public Response setOrgPhoto(@PathParam("organizationId") String organizationId, MultipartFormDataInput input) { // Look up organization with incl. the roles of the current subject in relation to the organization UserOrganization organization = organizationService.getUserOrganization(organizationId, getSubject().getUserId()); // Operation only allowed for site or organization admins if (!hasSiteRole("admin") && !hasOrganizationRole(organization, "admin")) { throw new WebApplicationException("User is not authorized to updated organization photo ", Response.Status.UNAUTHORIZED); } //Get API input data Map<String, List<InputPart>> uploadForm = input.getFormDataMap(); //Get file data to save List<InputPart> inputParts = uploadForm.get("attachment"); try { if (inputParts != null && inputParts.size() > 0) { InputPart inputPart = inputParts.get(0); // convert the uploaded file to input stream InputStream inputStream = inputPart.getBody(InputStream.class, null); // If not PNG, convert it byte[] bytes; String fileName = getFileName(inputPart.getHeaders()); if (fileName == null || !fileName.toLowerCase().endsWith(".png")) { BufferedImage image = ImageIO.read(inputStream); ByteArrayOutputStream pngImage = new ByteArrayOutputStream(); ImageIO.write(image, "png", pngImage); bytes = pngImage.toByteArray(); } else { // Already a PNG image bytes = IOUtils.toByteArray(inputStream); } organization.setLogo(bytes); organizationService.updateOrganization(organization); } } catch (Exception e) { log.error("Error uploading logo", e); return Response.serverError().build(); } return Response.status(201).entity(getOrganization(organizationId)).build(); }
From source file:com.tremolosecurity.scale.totp.TotpController.java
@PostConstruct public void init() { this.error = null; HttpServletRequest request = (HttpServletRequest) FacesContext.getCurrentInstance().getExternalContext() .getRequest();/*from w ww. j a v a 2 s.c o m*/ this.scaleTotpConfig = (ScaleTOTPConfigType) commonConfig.getScaleConfig(); this.login = request.getRemoteUser(); UnisonUserData userData; try { userData = this.scaleSession.loadUserFromUnison(this.login, new AttributeData(scaleTotpConfig.getServiceConfiguration().getLookupAttributeName(), scaleTotpConfig.getUiConfig().getDisplayNameAttribute(), scaleTotpConfig.getAttributeName())); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); return; } this.user = userData.getUserObj(); this.displayName = userData.getUserObj().getDisplayName(); ScaleAttribute scaleAttr = userData.getUserObj().getAttrs().get(scaleTotpConfig.getAttributeName()); if (scaleAttr == null) { if (logger.isDebugEnabled()) logger.debug("no sattribute"); this.error = "Token not found"; return; } this.encryptedToken = scaleAttr.getValue(); try { byte[] decryptionKeyBytes = Base64.decodeBase64(scaleTotpConfig.getDecryptionKey().getBytes("UTF-8")); SecretKey decryptionKey = new SecretKeySpec(decryptionKeyBytes, 0, decryptionKeyBytes.length, "AES"); Gson gson = new Gson(); Token token = gson.fromJson(new String(Base64.decodeBase64(this.encryptedToken.getBytes("UTF-8"))), Token.class); byte[] iv = org.bouncycastle.util.encoders.Base64.decode(token.getIv()); IvParameterSpec spec = new IvParameterSpec(iv); Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding"); cipher.init(Cipher.DECRYPT_MODE, decryptionKey, spec); String decryptedJSON = new String( cipher.doFinal(Base64.decodeBase64(token.getEncryptedRequest().getBytes("UTF-8")))); if (logger.isDebugEnabled()) logger.debug(decryptedJSON); TOTPKey totp = gson.fromJson(decryptedJSON, TOTPKey.class); this.otpURL = "otpauth://totp/" + totp.getUserName() + "@" + totp.getHost() + "?secret=" + totp.getSecretKey(); } catch (Exception e) { e.printStackTrace(); this.error = "Could not decrypt token"; } try { int size = 250; Hashtable<EncodeHintType, ErrorCorrectionLevel> hintMap = new Hashtable<EncodeHintType, ErrorCorrectionLevel>(); hintMap.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.L); QRCodeWriter qrCodeWriter = new QRCodeWriter(); BitMatrix byteMatrix = qrCodeWriter.encode(this.otpURL, BarcodeFormat.QR_CODE, size, size, hintMap); int CrunchifyWidth = byteMatrix.getWidth(); BufferedImage image = new BufferedImage(CrunchifyWidth, CrunchifyWidth, BufferedImage.TYPE_INT_RGB); image.createGraphics(); Graphics2D graphics = (Graphics2D) image.getGraphics(); graphics.setColor(Color.WHITE); graphics.fillRect(0, 0, CrunchifyWidth, CrunchifyWidth); graphics.setColor(Color.BLACK); for (int i = 0; i < CrunchifyWidth; i++) { for (int j = 0; j < CrunchifyWidth; j++) { if (byteMatrix.get(i, j)) { graphics.fillRect(i, j, 1, 1); } } } ByteArrayOutputStream baos = new ByteArrayOutputStream(); ImageIO.write(image, "png", baos); this.encodedQRCode = new String(Base64.encodeBase64(baos.toByteArray())); } catch (Exception e) { e.printStackTrace(); this.error = "Could not encode QR Code"; } }
From source file:com.mikenimer.familydam.services.photos.ThumbnailService.java
@Override protected void doGet(SlingHttpServletRequest request, SlingHttpServletResponse response) throws SlingServletException, IOException { if (ResourceUtil.isNonExistingResource(request.getResource())) { throw new ResourceNotFoundException("No data to render."); }//from ww w.j av a 2 s.com try { Session session = request.getResourceResolver().adaptTo(Session.class); Node parentNode = session.getNode(request.getResource().getPath()); Resource resource = request.getResource(); // first see if the etag header exists and we can skip processing. if (checkAndSetCacheHeaders(request, response, resource)) return; // check for a size selector int width = -1; int height = -1; //-1 means ignore and only set the width to resize final String[] selectors = request.getRequestPathInfo().getSelectors(); if (selectors != null && selectors.length > 0) { final String selector = selectors[selectors.length - 1].toLowerCase().trim(); if (selector.startsWith("w:")) { width = Integer.parseInt(selector.substring(2)); } if (selector.startsWith("h:")) { height = Integer.parseInt(selector.substring(2)); } } // check cache first if (checkForCachedImage(request, response)) return; //resize image //InputStream stream = node.getProperty("jcr:data").getBinary().getStream(); InputStream stream = resource.adaptTo(InputStream.class); int orientation = 1; if (stream != null) { try { Node n = parentNode.getNode("metadata"); if (n != null) { String _orientation = n.getProperty("orientation").getString(); if (StringUtils.isNumeric(_orientation)) { orientation = new Integer(_orientation); } } } catch (Exception ex) { } BufferedImage bi = ImageIO.read(stream); BufferedImage scaledImage = getScaledImage(bi, orientation, width, height); // cache the image long modTime = System.currentTimeMillis(); imageCache.put(request.getPathInfo(), scaledImage); timeGeneratedCache.put(request.getPathInfo(), modTime); //return the image response.setContentType("image/png"); response.setHeader(HttpConstants.HEADER_LAST_MODIFIED, new Long(modTime).toString()); //write bytes and png thumbnail ImageIO.write(scaledImage, "png", response.getOutputStream()); stream.close(); response.getOutputStream().flush(); } } catch (Exception ex) { // return original file. Resource resource = request.getResource(); InputStream stream = resource.adaptTo(InputStream.class); response.setContentType(resource.getResourceMetadata().getContentType()); response.setContentLength(new Long(resource.getResourceMetadata().getContentLength()).intValue()); //write bytes OutputStream out = response.getOutputStream(); byte[] buffer = new byte[1024]; while (true) { int bytesRead = stream.read(buffer); if (bytesRead < 0) break; out.write(buffer, 0, bytesRead); } stream.close(); response.getOutputStream().flush(); } }
From source file:org.ednovo.gooru.application.converter.GooruImageUtil.java
public static void cropImage(String path, int x, int y, int width, int height) throws Exception { BufferedImage srcImg = ImageIO.read(new File(path)); srcImg = srcImg.getSubimage(x, y, width, height); ImageIO.write(srcImg, PNG, new File(path)); }
From source file:com.qihang.winter.poi.excel.export.base.ExcelExportBase.java
/** * Cell//from ww w .j av a 2 s . c o m * * @param patriarch * @param entity * @param row * @param i * @param imagePath * @param obj * @throws Exception */ public void createImageCell(Drawing patriarch, com.qihang.winter.poi.excel.entity.params.ExcelExportEntity entity, Row row, int i, String imagePath, Object obj) throws Exception { row.setHeight((short) (50 * entity.getHeight())); row.createCell(i); ClientAnchor anchor; if (type.equals(com.qihang.winter.poi.excel.entity.enmus.ExcelType.HSSF)) { anchor = new HSSFClientAnchor(0, 0, 0, 0, (short) i, row.getRowNum(), (short) (i + 1), row.getRowNum() + 1); } else { anchor = new XSSFClientAnchor(0, 0, 0, 0, (short) i, row.getRowNum(), (short) (i + 1), row.getRowNum() + 1); } if (StringUtils.isEmpty(imagePath)) { return; } if (entity.getExportImageType() == 1) { ByteArrayOutputStream byteArrayOut = new ByteArrayOutputStream(); BufferedImage bufferImg; try { String path = PoiPublicUtil.getWebRootPath(imagePath); path = path.replace("WEB-INF/classes/", ""); path = path.replace("file:/", ""); bufferImg = ImageIO.read(new File(path)); ImageIO.write(bufferImg, imagePath.substring(imagePath.indexOf(".") + 1, imagePath.length()), byteArrayOut); byte[] value = byteArrayOut.toByteArray(); patriarch.createPicture(anchor, row.getSheet().getWorkbook().addPicture(value, getImageType(value))); } catch (IOException e) { LOGGER.error(e.getMessage(), e); } } else { byte[] value = (byte[]) (entity.getMethods() != null ? getFieldBySomeMethod(entity.getMethods(), obj) : entity.getMethod().invoke(obj, new Object[] {})); if (value != null) { patriarch.createPicture(anchor, row.getSheet().getWorkbook().addPicture(value, getImageType(value))); } } }
From source file:com.partagames.imageresizetool.SimpleImageResizeTool.java
/** * Resizes and writes the images to the given or default output folder. *//*from w w w.j a va2 s .com*/ private static void resizeAndWriteImages() { File outputFolderFile; // if output folder is given as cli option if (outputFolder != null) { outputFolderFile = outputFolder.toFile(); if (!outputFolderFile.exists()) { outputFolderFile.mkdirs(); } } else { // default output folder outputFolderFile = new File("output/"); if (!outputFolderFile.exists()) { outputFolderFile.mkdirs(); } } // resize and write images for (String key : imageFiles.keySet()) { final String fileName = extractFileNameFromPath(key); final BufferedImage image = imageFiles.get(key); final BufferedImage scaledImage = scale(image, dimensions.width, dimensions.height); try { ImageIO.write(scaledImage, format, new File(outputFolderFile.getPath() + "/" + dimensions.width + "_x_" + dimensions.height + "_" + fileName + "." + format)); } catch (IOException e) { System.out.println("Error: Cannot write " + key + " to output folder. Ignoring..."); } } }