List of usage examples for java.awt.image BufferedImage getType
public int getType()
From source file:org.mycore.iview2.frontend.MCRTileCombineServlet.java
/** * attaches <code>footer</code> to <code>combinedImage</code>. * @param combinedImage image to attach footer to * @param footer image of same with as <code>combinedImage</code> * @return a {@link BufferedImage} with <code>footer</code> attached to <code>combinedImage</code> *///w w w. j a v a 2 s . c o m protected static BufferedImage attachFooter(final BufferedImage combinedImage, final BufferedImage footer) { final BufferedImage resultImage = new BufferedImage(combinedImage.getWidth(), combinedImage.getHeight() + footer.getHeight(), combinedImage.getType()); final Graphics2D graphics = resultImage.createGraphics(); try { graphics.drawImage(combinedImage, 0, 0, null); graphics.drawImage(footer, 0, combinedImage.getHeight(), null); return resultImage; } finally { graphics.dispose(); } }
From source file:org.niord.web.wms.WmsProxyServlet.java
/** * Masks out white colour// w ww.ja va2 s . co m * @param image the image to mask out * @return the resulting image */ @SuppressWarnings("unused") private BufferedImage transformWhiteToTransparent(BufferedImage image) { BufferedImage dest = image; if (image.getType() != BufferedImage.TYPE_INT_ARGB) { dest = new BufferedImage(image.getWidth(null), image.getHeight(null), BufferedImage.TYPE_INT_ARGB); Graphics2D g2 = dest.createGraphics(); g2.drawImage(image, 0, 0, null); g2.dispose(); image.flush(); } // Mask out the white pixels final int width = image.getWidth(); int[] imgData = new int[width]; for (int y = 0; y < dest.getHeight(); y++) { // fetch a line of data from each image dest.getRGB(0, y, width, 1, imgData, 0, 1); // apply the mask for (int x = 0; x < width; x++) { for (Color col : MASKED_COLORS) { int colDist = Math.abs(col.getRed() - (imgData[x] >> 16 & 0x000000FF)) + Math.abs(col.getGreen() - (imgData[x] >> 8 & 0x000000FF)) + Math.abs(col.getBlue() - (imgData[x] & 0x000000FF)); if (colDist <= COLOR_DIST) { imgData[x] = 0x00FFFFFF & imgData[x]; } } } // replace the data dest.setRGB(0, y, width, 1, imgData, 0, 1); } return dest; }
From source file:org.ofbiz.product.imagemanagement.ImageManagementServices.java
public static Map<String, Object> resizeImageThumbnail(BufferedImage bufImg, double imgHeight, double imgWidth) { /* VARIABLES */ BufferedImage bufNewImg;/*from ww w . j a v a 2 s . co m*/ double defaultHeight, defaultWidth, scaleFactor; Map<String, Object> result = FastMap.newInstance(); /* DIMENSIONS from ImageProperties */ defaultHeight = 100; defaultWidth = 100; /* SCALE FACTOR */ // find the right Scale Factor related to the Image Dimensions if (imgHeight > imgWidth) { scaleFactor = defaultHeight / imgHeight; // get scaleFactor from the smallest width if (defaultWidth < (imgWidth * scaleFactor)) { scaleFactor = defaultWidth / imgWidth; } } else { scaleFactor = defaultWidth / imgWidth; // get scaleFactor from the smallest height if (defaultHeight < (imgHeight * scaleFactor)) { scaleFactor = defaultHeight / imgHeight; } } int bufImgType; if (BufferedImage.TYPE_CUSTOM == bufImg.getType()) { // apply a type for image majority bufImgType = BufferedImage.TYPE_INT_ARGB_PRE; } else { bufImgType = bufImg.getType(); } // scale original image with new size Image newImg = bufImg.getScaledInstance((int) (imgWidth * scaleFactor), (int) (imgHeight * scaleFactor), Image.SCALE_SMOOTH); bufNewImg = ImageTransform.toBufferedImage(newImg, bufImgType); result.put("bufferedImage", bufNewImg); result.put("scaleFactor", scaleFactor); return result; }
From source file:org.ofbiz.product.imagemanagement.ImageManagementServices.java
public static Map<String, Object> resizeImage(BufferedImage bufImg, double imgHeight, double imgWidth, double resizeHeight, double resizeWidth) { /* VARIABLES */ BufferedImage bufNewImg;/*w ww . j a v a 2s .c o m*/ double defaultHeight, defaultWidth, scaleFactor; Map<String, Object> result = FastMap.newInstance(); /* DIMENSIONS from ImageProperties */ defaultHeight = resizeHeight; defaultWidth = resizeWidth; /* SCALE FACTOR */ // find the right Scale Factor related to the Image Dimensions if (imgHeight > imgWidth) { scaleFactor = defaultHeight / imgHeight; // get scaleFactor from the smallest width if (defaultWidth < (imgWidth * scaleFactor)) { scaleFactor = defaultWidth / imgWidth; } } else { scaleFactor = defaultWidth / imgWidth; // get scaleFactor from the smallest height if (defaultHeight < (imgHeight * scaleFactor)) { scaleFactor = defaultHeight / imgHeight; } } int bufImgType; if (BufferedImage.TYPE_CUSTOM == bufImg.getType()) { // apply a type for image majority bufImgType = BufferedImage.TYPE_INT_ARGB_PRE; } else { bufImgType = bufImg.getType(); } // scale original image with new size Image newImg = bufImg.getScaledInstance((int) (imgWidth * scaleFactor), (int) (imgHeight * scaleFactor), Image.SCALE_SMOOTH); bufNewImg = ImageTransform.toBufferedImage(newImg, bufImgType); result.put("bufferedImage", bufNewImg); result.put("scaleFactor", scaleFactor); return result; }
From source file:org.olat.core.commons.services.image.spi.ImageHelperImpl.java
/** * This code is very inspired on Chris Campbells article "The Perils of Image.getScaledInstance()" * * The article can be found here:/* w ww .j a v a2s . com*/ * http://today.java.net/pub/a/today/2007/04/03/perils-of-image-getscaledinstance.html * * Note that the filter method is threadsafe */ private static BufferedImage scaleFastTo(BufferedImage img, Size scaledSize) { if (!scaledSize.isChanged()) return img; BufferedImage dest; if (img.getType() == BufferedImage.TYPE_CUSTOM) { dest = new BufferedImage(scaledSize.getWidth(), scaledSize.getHeight(), BufferedImage.TYPE_INT_ARGB); } else { dest = new BufferedImage(scaledSize.getWidth(), scaledSize.getHeight(), img.getType()); } int dstWidth = scaledSize.getWidth(); int dstHeight = scaledSize.getHeight(); BufferedImage ret = img; int w, h; // Use multi-step technique: start with original size, then // scale down in multiple passes with drawImage() // until the target size is reached w = img.getWidth(); h = img.getHeight(); int x = scaledSize.getXOffset(); int y = scaledSize.getYOffset(); //crop the image to see only the center of the image if (x > 0 || y > 0) { ret = img.getSubimage(x, y, w - (2 * x), h - (2 * y)); } do { if (w > dstWidth) { if (x > 0) { x /= 2; } w /= 2; if (w < dstWidth) { w = dstWidth; } } else { w = dstWidth; } if (h > dstHeight) { h /= 2; if (h < dstHeight) { h = dstHeight; } } else { h = dstHeight; } BufferedImage tmp; if (dest.getWidth() == w && dest.getHeight() == h && w == dstWidth && h == dstHeight) { tmp = dest; } else { tmp = new BufferedImage(w, h, dest.getType()); } Graphics2D g2 = tmp.createGraphics(); g2.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR); g2.drawImage(ret, 0, 0, w, h, null); g2.dispose(); ret = tmp; } while (w != dstWidth || h != dstHeight); return ret; }
From source file:org.openbravo.erpCommon.utility.Utility.java
/** * Resize an image giving the image input as byte[] * //from w ww .j a v a 2s . co m * @param bytea * The contents of the image as a byte array * @param maxW * Maximum width that the image will be resized. * @param maxH * Maximum height that the image will be resized. * @param maintainAspectRatio * If true, the image will be resized exactly to the maximum parameters. If false, the * imagen will be resized closest to the maximum parameters keeping aspect ratio * @param canMakeLargerImage * If true and the original image is smaller than maximum parameters, the resized image * could be larger than the original one. If false, not. * @return The resized image */ public static byte[] resizeImageByte(byte[] bytea, int maxW, int maxH, boolean maintainAspectRatio, boolean canMakeLargerImage) throws IOException { ByteArrayInputStream bis = new ByteArrayInputStream(bytea); BufferedImage rImage = ImageIO.read(bis); int newW = maxW; int newH = maxH; int oldW = rImage.getWidth(); int oldH = rImage.getHeight(); if (newW == 0 && newH == 0) { return bytea; } else if (newW == 0) { if (maintainAspectRatio) { newW = 99999; } else { newW = oldW; } } else if (newH == 0) { if (maintainAspectRatio) { newH = 99999; } else { newH = oldH; } } if (oldW == newW && oldH == newH) { return bytea; } if (!canMakeLargerImage && newW > oldW && newH > oldH) { return bytea; } if (maintainAspectRatio) { float oldRatio = (float) oldW / (float) oldH; float newRatio = (float) newW / (float) newH; if (oldRatio < newRatio) { newW = (int) (newH * oldRatio); } else if (oldRatio > newRatio) { newH = (int) (newW / oldRatio); } } BufferedImage dimg = new BufferedImage(newW, newH, rImage.getType()); Graphics2D g = dimg.createGraphics(); g.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR); g.drawImage(rImage, 0, 0, newW, newH, 0, 0, oldW, oldH, null); g.dispose(); ByteArrayOutputStream baos = new ByteArrayOutputStream(); String mimeType = MimeTypeUtil.getInstance().getMimeTypeName(bytea); if (mimeType.contains("jpeg")) { mimeType = "jpeg"; } else if (mimeType.contains("png")) { mimeType = "png"; } else if (mimeType.contains("gif")) { mimeType = "gif"; } else if (mimeType.contains("bmp")) { mimeType = "bmp"; } else { return bytea; } ImageIO.write(dimg, mimeType, baos); byte[] bytesOut = baos.toByteArray(); return bytesOut; }
From source file:org.sbs.util.ImageCompress.java
/** * ?//from w ww. java2 s . com * * @param source * @param targetW * @param targetH * @return */ public BufferedImage resize(BufferedImage source, int targetW, int targetH) { // targetWtargetH int desH = 0; int type = source.getType(); BufferedImage target = null; double sx = (double) targetW / source.getWidth(); double sy = sx; desH = (int) (sx * source.getHeight()); if (desH < targetH) { desH = targetH; sy = (double) 61 / source.getHeight(); } if (type == BufferedImage.TYPE_CUSTOM) { // handmade ColorModel cm = source.getColorModel(); WritableRaster raster = cm.createCompatibleWritableRaster(targetW, desH); boolean alphaPremultiplied = cm.isAlphaPremultiplied(); target = new BufferedImage(cm, raster, alphaPremultiplied, null); } else target = new BufferedImage(targetW, desH, type); Graphics2D g = target.createGraphics(); // smoother than exlax: g.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BICUBIC); g.drawRenderedImage(source, AffineTransform.getScaleInstance(sx, sy)); g.dispose(); return target; }
From source file:org.sharegov.cirm.utils.PhotoUploadResource.java
/** * Accepts and processes a representation posted to the resource. As * response, the content of the uploaded file is sent back the client. */// w ww. ja va2 s . c o m @Post public Representation accept(Representation entity) { // NOTE: the return media type here is TEXT_HTML because IE opens up a file download box // if it's APPLICATION_JSON as we'd want it. Representation rep = new StringRepresentation(GenUtils.ko("Unable to upload, bad request.").toString(), MediaType.TEXT_HTML); if (entity != null) { if (MediaType.MULTIPART_FORM_DATA.equals(entity.getMediaType(), true)) { // 1/ Create a factory for disk-based file items // DiskFileItemFactory factory = new DiskFileItemFactory(); // factory.setSizeThreshold(1000240); // 2/ Create a new file upload handler based on the Restlet // FileUpload extension that will parse Restlet requests and // generates FileItems. RestletFileUpload upload = new RestletFileUpload(); // List<FileItem> items; // // // 3/ Request is parsed by the handler which generates a // // list of FileItems InputStream is = null; Graphics2D g = null; FileOutputStream fos = null; ByteArrayOutputStream baos = null; try { FileItemIterator fit = upload.getItemIterator(entity); while (fit.hasNext()) { FileItemStream stream = fit.next(); if (stream.getFieldName().equals("uploadImage")) { String contentType = stream.getContentType(); if (contentType.startsWith("image")) { String extn = contentType.substring(contentType.indexOf("/") + 1); byte[] data = GenUtils.getBytesFromStream(stream.openStream(), true); String filename = "image_" + Refs.idFactory.resolve().newId(null) + "." + extn; //String filename = "srphoto_123" + "."+extn; // + OWLRefs.idFactory.resolve().newId("Photo"); // may add Photo class to ontology File f = new File(StartUp.config.at("workingDir").asString() + "/src/uploaded", filename); StringBuilder sb = new StringBuilder(""); String hostname = java.net.InetAddress.getLocalHost().getHostName(); boolean ssl = StartUp.config.is("ssl", true); int port = ssl ? StartUp.config.at("ssl-port").asInteger() : StartUp.config.at("port").asInteger(); if (ssl) sb.append("https://"); else sb.append("http://"); sb.append(hostname); if ((ssl && port != 443) || (!ssl && port != 80)) sb.append(":").append(port); sb.append("/uploaded/"); sb.append(filename); //Start : resize Image int rw = 400; int rh = 300; is = new ByteArrayInputStream(data); BufferedImage image = ImageIO.read(is); int w = image.getWidth(); int h = image.getHeight(); if (w > rw) { BufferedImage bi = new BufferedImage(rw, rh, image.getType()); g = bi.createGraphics(); g.drawImage(image, 0, 0, rw, rh, null); baos = new ByteArrayOutputStream(); ImageIO.write(bi, extn, baos); data = baos.toByteArray(); } //End: resize Image fos = new FileOutputStream(f); fos.write(data); Json j = GenUtils.ok().set("image", sb.toString()); //Json j = GenUtils.ok().set("image", filename); rep = new StringRepresentation(j.toString(), (MediaType) MediaType.TEXT_HTML); } else { rep = new StringRepresentation(GenUtils.ko("Please upload only Images.").toString(), MediaType.TEXT_HTML); } } } } catch (Exception e) { e.printStackTrace(); } finally { if (fos != null) { try { fos.flush(); fos.close(); } catch (IOException e) { } } if (is != null) { try { is.close(); } catch (IOException e) { } } if (baos != null) { try { baos.flush(); baos.close(); } catch (IOException e) { } } if (g != null) { g.dispose(); } } } } else { // POST request with no entity. setStatus(Status.CLIENT_ERROR_BAD_REQUEST); } return rep; }
From source file:org.springframework.cloud.stream.app.object.detection.processor.ObjectDetectionTensorflowInputConverter.java
private static Tensor<UInt8> makeImageTensor(byte[] imageBytes) throws IOException { ByteArrayInputStream is = new ByteArrayInputStream(imageBytes); BufferedImage img = ImageIO.read(is); if (img.getType() != BufferedImage.TYPE_3BYTE_BGR) { throw new IllegalArgumentException( String.format("Expected 3-byte BGR encoding in BufferedImage, found %d", img.getType())); }//from w w w.ja v a2s . c om byte[] data = ((DataBufferByte) img.getData().getDataBuffer()).getData(); // ImageIO.read produces BGR-encoded images, while the model expects RGB. bgrToRgb(data); //Expand dimensions since the model expects images to have shape: [1, None, None, 3] long[] shape = new long[] { BATCH_SIZE, img.getHeight(), img.getWidth(), CHANNELS }; return Tensor.create(UInt8.class, shape, ByteBuffer.wrap(data)); }
From source file:org.springframework.cloud.stream.app.pose.estimation.processor.PoseEstimationTensorflowInputConverter.java
private Tensor<Float> makeImageTensor(byte[] imageBytes) throws IOException { ByteArrayInputStream is = new ByteArrayInputStream(imageBytes); BufferedImage img = ImageIO.read(is); if (img.getType() != BufferedImage.TYPE_3BYTE_BGR) { throw new IllegalArgumentException( String.format("Expected 3-byte BGR encoding in BufferedImage, found %d", img.getType())); }/*from ww w .j a v a2 s .c o m*/ // ImageIO.read produces BGR-encoded images, while the model expects RGB. int[] data = toIntArray(img); //Expand dimensions since the model expects images to have shape: [1, None, None, 3] long[] shape = new long[] { BATCH_SIZE, img.getHeight(), img.getWidth(), CHANNELS }; return Tensor.create(shape, FloatBuffer.wrap(toRgbFloat(data))); }