List of usage examples for java.awt.image BufferedImage TYPE_3BYTE_BGR
int TYPE_3BYTE_BGR
To view the source code for java.awt.image BufferedImage TYPE_3BYTE_BGR.
Click Source Link
From source file:ImageBouncer.java
public void setImageType(String s) { int type = BufferedImage.TYPE_CUSTOM; if (s.equals("TYPE_INT_RGB")) type = BufferedImage.TYPE_INT_RGB; else if (s.equals("TYPE_INT_ARGB")) type = BufferedImage.TYPE_INT_ARGB; else if (s.equals("TYPE_INT_ARGB_PRE")) type = BufferedImage.TYPE_INT_ARGB_PRE; else if (s.equals("TYPE_3BYTE_BGR")) type = BufferedImage.TYPE_3BYTE_BGR; else if (s.equals("TYPE_BYTE_GRAY")) type = BufferedImage.TYPE_BYTE_GRAY; else if (s.equals("TYPE_USHORT_GRAY")) type = BufferedImage.TYPE_USHORT_GRAY; else if (s.equals("TYPE_USHORT_555_RGB")) type = BufferedImage.TYPE_USHORT_565_RGB; else if (s.equals("TYPE_USHORT_565_RGB")) type = BufferedImage.TYPE_USHORT_565_RGB; else {/* w ww . ja v a 2 s . co m*/ System.out.println("Unrecognized type."); return; } image = makeBufferedImage(mOriginalImage, type); }
From source file:nl.ru.ai.projects.parrot.tools.TwitterAccess.java
/** * Returns a RenderedImage object from a byte array * @param cameraOutput The camera output to transform into a RenderedImage * @return The RenderedImage that resulted from the camera output *///from w w w .j a va 2 s . co m private RenderedImage getImageFromCamera(byte[] cameraOutput) { BufferedImage image = new BufferedImage(VideoPollInterface.FRONT_VIDEO_FRAME_WIDTH, VideoPollInterface.FRONT_VIDEO_FRAME_HEIGHT, BufferedImage.TYPE_3BYTE_BGR); if (cameraOutput != null) { WritableRaster raster = Raster.createBandedRaster(DataBuffer.TYPE_BYTE, VideoPollInterface.FRONT_VIDEO_FRAME_WIDTH, VideoPollInterface.FRONT_VIDEO_FRAME_HEIGHT, 3, new Point(0, 0)); raster.setDataElements(0, 0, VideoPollInterface.FRONT_VIDEO_FRAME_WIDTH, VideoPollInterface.FRONT_VIDEO_FRAME_HEIGHT, cameraOutput); image.setData(raster); } return image; }
From source file:org.opencms.pdftools.CmsPdfThumbnailGenerator.java
/** * Generates the image data for a thumbnail from a PDF.<p> * * The given width and height determine the box in which the thumbnail should fit. * The resulting image will always have these dimensions, even if the aspect ratio of the actual PDF * page is different from the ratio of the given width and height. In this case, the size of the rendered * page will be reduced, and the rest of the image will be filled with blank space.<p> * * If one of width or height is negative, then that dimension is chosen so the resulting aspect ratio is the * aspect ratio of the PDF page.//from w w w . jav a2 s . c o m * * @param pdfInputStream the input stream for reading the PDF data * @param boxWidth the width of the box in which the thumbnail should fit * @param boxHeight the height of the box in which the thumbnail should fit * @param imageFormat the image format (png, jpg, gif) * @param pageIndex the index of the page for which to render the thumbnail (starting at 0) * * @return the image data for the thumbnail, in the given image format * @throws Exception if something goes wrong */ public byte[] generateThumbnail(InputStream pdfInputStream, int boxWidth, int boxHeight, String imageFormat, int pageIndex) throws Exception { org.jpedal.io.ObjectStore.temp_dir = CmsFileUtil.normalizePath(OpenCms.getSystemInfo().getWebInfRfsPath() + CmsPdfThumbnailCache.PDF_CACHE_FOLDER + File.separatorChar); PdfDecoder decoder = new PdfDecoder(true); try { decoder.openPdfFileFromInputStream(pdfInputStream, false); int numPages = decoder.getPageCount(); if (pageIndex >= numPages) { pageIndex = numPages - 1; } else if (pageIndex < 0) { pageIndex = 0; } // width/height are in points (1/72 of an inch) PdfPageData pageData = decoder.getPdfPageData(); double aspectRatio = (pageData.getCropBoxWidth(1 + pageIndex) * 1.0) / pageData.getCropBoxHeight(1 + pageIndex); int rotation = pageData.getRotation(1 + pageIndex); if ((rotation == 90) || (rotation == 270)) { // landscape aspectRatio = 1 / aspectRatio; } if ((boxWidth < 0) && (boxHeight < 0)) { throw new IllegalArgumentException("At least one of width / height must be positive!"); } else if ((boxWidth < 0) && (boxHeight > 0)) { boxWidth = (int) Math.round(aspectRatio * boxHeight); } else if ((boxWidth > 0) && (boxHeight < 0)) { boxHeight = (int) Math.round(boxWidth / aspectRatio); } // calculateDimensions only takes integers, but only their ratio matters, we multiply the box width with a big number int fakePixelWidth = (int) (FAKE_PIXEL_MULTIPLIER * aspectRatio); int fakePixelHeight = (FAKE_PIXEL_MULTIPLIER); int[] unpaddedThumbnailDimensions = CmsImageScaler.calculateDimension(fakePixelWidth, fakePixelHeight, boxWidth, boxHeight); decoder.decodePage(1 + pageIndex); BufferedImage pageImage = decoder.getPageAsImage(1 + pageIndex); BufferedImage paddedImage = new BufferedImage(boxWidth, boxHeight, BufferedImage.TYPE_3BYTE_BGR); Graphics2D g = paddedImage.createGraphics(); int uw = unpaddedThumbnailDimensions[0]; int uh = unpaddedThumbnailDimensions[1]; // Scale to fit in the box AffineTransformOp op = new AffineTransformOp(AffineTransform .getScaleInstance((uw * 1.0) / pageImage.getWidth(), (uh * 1.0) / pageImage.getHeight()), AffineTransformOp.TYPE_BILINEAR); g.setColor(Color.WHITE); // Fill box image with white, then draw the image data for the PDF in the middle g.fillRect(0, 0, paddedImage.getWidth(), paddedImage.getHeight()); //g.drawImage(pageImage, (boxWidth - pageImage.getWidth()) / 2, (boxHeight - pageImage.getHeight()) / 2, null); g.drawImage(pageImage, op, (boxWidth - uw) / 2, (boxHeight - uh) / 2); BufferedImage pageThumbnail = paddedImage; ByteArrayOutputStream out = new ByteArrayOutputStream(); ImageIOUtil.writeImage(pageThumbnail, imageFormat, out); byte[] imageData = out.toByteArray(); return imageData; } finally { if (decoder.isOpen()) { decoder.closePdfFile(); } pdfInputStream.close(); } }
From source file:org.b3log.symphony.service.AvatarQueryService.java
/** * Creates a avatar image with the specified hash string and size. * * <p>//from www. j av a2 s. co m * Refers to: https://github.com/superhj1987/awesome-identicon * </p> * * @param hash the specified hash string * @param size the specified size * @return buffered image */ public BufferedImage createAvatar(final String hash, final int size) { final boolean[][] array = new boolean[6][5]; for (int i = 0; i < 6; i++) { for (int j = 0; j < 5; j++) { array[i][j] = false; } } for (int i = 0; i < hash.length(); i += 2) { final int s = i / 2; final boolean v = Math.random() > 0.5; if (s % 3 == 0) { array[s / 3][0] = v; array[s / 3][4] = v; } else if (s % 3 == 1) { array[s / 3][1] = v; array[s / 3][3] = v; } else { array[s / 3][2] = v; } } final int ratio = Math.round(size / 5); final BufferedImage ret = new BufferedImage(ratio * 5, ratio * 5, BufferedImage.TYPE_3BYTE_BGR); final Graphics graphics = ret.getGraphics(); graphics.setColor(new Color(Integer.parseInt(String.valueOf(hash.charAt(0)), 16) * 16, Integer.parseInt(String.valueOf(hash.charAt(1)), 16) * 16, Integer.parseInt(String.valueOf(hash.charAt(2)), 16) * 16)); graphics.fillRect(0, 0, ret.getWidth(), ret.getHeight()); graphics.setColor(new Color(Integer.parseInt(String.valueOf(hash.charAt(hash.length() - 1)), 16) * 16, Integer.parseInt(String.valueOf(hash.charAt(hash.length() - 2)), 16) * 16, Integer.parseInt(String.valueOf(hash.charAt(hash.length() - 3)), 16) * 16)); for (int i = 0; i < 6; i++) { for (int j = 0; j < 5; j++) { if (array[i][j]) { graphics.fillRect(j * ratio, i * ratio, ratio, ratio); } } } return ret; }
From source file:com.frochr123.fabqr.FabQRFunctions.java
public static void uploadFabQRProject(String name, String email, String projectName, int licenseIndex, String tools, String description, String location, BufferedImage imageReal, BufferedImage imageScheme, PlfFile plfFile, String lasercutterName, String lasercutterMaterial) throws Exception { // Check for valid situation, otherwise abort if (MainView.getInstance() == null || VisicutModel.getInstance() == null || VisicutModel.getInstance().getPlfFile() == null || !isFabqrActive() || getFabqrPrivateURL() == null || getFabqrPrivateURL().isEmpty() || MaterialManager.getInstance() == null || MappingManager.getInstance() == null || VisicutModel.getInstance().getSelectedLaserDevice() == null) { throw new Exception("FabQR upload exception: Critical error"); }/*w w w . j a va2 s.co m*/ // Check valid data if (name == null || email == null || projectName == null || projectName.length() < 3 || licenseIndex < 0 || tools == null || tools.isEmpty() || description == null || description.isEmpty() || location == null || location.isEmpty() || imageScheme == null || plfFile == null || lasercutterName == null || lasercutterName.isEmpty() || lasercutterMaterial == null || lasercutterMaterial.isEmpty()) { throw new Exception("FabQR upload exception: Invalid input data"); } // Convert images to byte data for PNG, imageReal is allowed to be empty byte[] imageSchemeBytes = null; ByteArrayOutputStream imageSchemeOutputStream = new ByteArrayOutputStream(); PreviewImageExport.writePngToOutputStream(imageSchemeOutputStream, imageScheme); imageSchemeBytes = imageSchemeOutputStream.toByteArray(); if (imageSchemeBytes == null) { throw new Exception("FabQR upload exception: Error converting scheme image"); } byte[] imageRealBytes = null; if (imageReal != null) { // Need to convert image, ImageIO.write messes up the color space of the original input image BufferedImage convertedImage = new BufferedImage(imageReal.getWidth(), imageReal.getHeight(), BufferedImage.TYPE_3BYTE_BGR); ColorConvertOp op = new ColorConvertOp(null); op.filter(imageReal, convertedImage); ByteArrayOutputStream imageRealOutputStream = new ByteArrayOutputStream(); ImageIO.write(convertedImage, "jpg", imageRealOutputStream); imageRealBytes = imageRealOutputStream.toByteArray(); } // Extract all URLs from used QR codes List<String> referencesList = new LinkedList<String>(); List<PlfPart> plfParts = plfFile.getPartsCopy(); for (PlfPart plfPart : plfParts) { if (plfPart.getQRCodeInfo() != null && plfPart.getQRCodeInfo().getQRCodeSourceURL() != null && !plfPart.getQRCodeInfo().getQRCodeSourceURL().trim().isEmpty()) { // Process url, if it is URL of a FabQR system, remove download flag and point to project page instead // Use regex to check for FabQR system URL structure String qrCodeUrl = plfPart.getQRCodeInfo().getQRCodeSourceURL().trim(); // Check for temporary URL structure of FabQR system Pattern fabQRUrlTemporaryPattern = Pattern .compile("^https{0,1}://.*?" + "/" + FABQR_TEMPORARY_MARKER + "/" + "([a-z]|[0-9]){7,7}$"); // Do not include link if it is just temporary if (fabQRUrlTemporaryPattern.matcher(qrCodeUrl).find()) { continue; } // Check for download URL structure of FabQR system // Change URL to point to project page instead Pattern fabQRUrlDownloadPattern = Pattern .compile("^https{0,1}://.*?" + "/" + FABQR_DOWNLOAD_MARKER + "/" + "([a-z]|[0-9]){7,7}$"); if (fabQRUrlDownloadPattern.matcher(qrCodeUrl).find()) { qrCodeUrl = qrCodeUrl.replace("/" + FABQR_DOWNLOAD_MARKER + "/", "/"); } // Add URL if it is not yet in list if (!referencesList.contains(qrCodeUrl)) { referencesList.add(qrCodeUrl); } } } String references = ""; for (String ref : referencesList) { // Add comma for non first entries if (!references.isEmpty()) { references = references + ","; } references = references + ref; } // Get bytes for PLF file byte[] plfFileBytes = null; ByteArrayOutputStream plfFileOutputStream = new ByteArrayOutputStream(); VisicutModel.getInstance().savePlfToStream(MaterialManager.getInstance(), MappingManager.getInstance(), plfFileOutputStream); plfFileBytes = plfFileOutputStream.toByteArray(); if (plfFileBytes == null) { throw new Exception("FabQR upload exception: Error saving PLF file"); } // Begin uploading data String uploadUrl = getFabqrPrivateURL() + FABQR_API_UPLOAD_PROJECT; // Create HTTP client and cusomized config for timeouts CloseableHttpClient httpClient = HttpClients.createDefault(); RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(FABQR_UPLOAD_TIMEOUT) .setConnectTimeout(FABQR_UPLOAD_TIMEOUT).setConnectionRequestTimeout(FABQR_UPLOAD_TIMEOUT).build(); // Create HTTP Post request and entity builder HttpPost httpPost = new HttpPost(uploadUrl); httpPost.setConfig(requestConfig); MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create(); // Insert file uploads multipartEntityBuilder.addBinaryBody("imageScheme", imageSchemeBytes, ContentType.APPLICATION_OCTET_STREAM, "imageScheme.png"); multipartEntityBuilder.addBinaryBody("inputFile", plfFileBytes, ContentType.APPLICATION_OCTET_STREAM, "inputFile.plf"); // Image real is allowed to be null, if it is not, send it if (imageRealBytes != null) { multipartEntityBuilder.addBinaryBody("imageReal", imageRealBytes, ContentType.APPLICATION_OCTET_STREAM, "imageReal.png"); } // Prepare content type for text data, especially needed for correct UTF8 encoding ContentType contentType = ContentType.create("text/plain", Consts.UTF_8); // Insert text data multipartEntityBuilder.addTextBody("name", name, contentType); multipartEntityBuilder.addTextBody("email", email, contentType); multipartEntityBuilder.addTextBody("projectName", projectName, contentType); multipartEntityBuilder.addTextBody("licenseIndex", new Integer(licenseIndex).toString(), contentType); multipartEntityBuilder.addTextBody("tools", tools, contentType); multipartEntityBuilder.addTextBody("description", description, contentType); multipartEntityBuilder.addTextBody("location", location, contentType); multipartEntityBuilder.addTextBody("lasercutterName", lasercutterName, contentType); multipartEntityBuilder.addTextBody("lasercutterMaterial", lasercutterMaterial, contentType); multipartEntityBuilder.addTextBody("references", references, contentType); // Assign entity to this post request HttpEntity httpEntity = multipartEntityBuilder.build(); httpPost.setEntity(httpEntity); // Set authentication information String encodedCredentials = Helper.getEncodedCredentials(FabQRFunctions.getFabqrPrivateUser(), FabQRFunctions.getFabqrPrivatePassword()); if (!encodedCredentials.isEmpty()) { httpPost.addHeader("Authorization", "Basic " + encodedCredentials); } // Send request CloseableHttpResponse res = httpClient.execute(httpPost); // React to possible server side errors if (res.getStatusLine() == null || res.getStatusLine().getStatusCode() != HttpStatus.SC_OK) { throw new Exception("FabQR upload exception: Server sent wrong HTTP status code: " + new Integer(res.getStatusLine().getStatusCode()).toString()); } // Close everything correctly res.close(); httpClient.close(); }
From source file:core.service.RubricImageCachingService.java
/** * generates image_quantity images for current page * image is made by drawing 4 images on one same images * the resulting images are in image_width * image_height resolution * @param p page to take images for// ww w .j a va2 s . c o m * @param dst_dir dir where to save resulting images * @return false if any error occurs */ protected boolean generateImages4(Pages p, File dst_dir) { boolean succeed = true; List<Long> ids = pages_service.getAllActiveChildrenId(p.getId()); List<Wallpaper> wallpapers = wallpaper_service.getMainImages(ids, 4); File src_dir = new File(wallpaper_service.getStorePath(), "full"); File src; BufferedImageHolder holder; BufferedImage[] src_img = new BufferedImage[wallpapers.size()]; BufferedImage rez; //creating src images for (int i = 0; i < wallpapers.size(); i++) { Wallpaper wallpaper = wallpapers.get(i); src = new File(src_dir, wallpaper.getName()); if (src.exists()) { try { holder = ImageUtils.readImage(src); rez = new BufferedImage((int) (image_width / 1.65), (int) (image_height / 1.65), BufferedImage.TYPE_3BYTE_BGR); ImageUtils.getScaledImageDimmension(holder.getImage(), rez); src_img[i] = rez; } catch (IOException ex) { logger.error("error while creating image for rubric; ", ex); succeed = false; } } else { logger.error("error while creating image for rubric; " + p.getId() + "; " + p.getName() + "; " + src.getName()); succeed = false; } } //drawing try { File dst = new File(dst_dir, Long.toString(System.nanoTime(), 10)); rez = new BufferedImage(image_width, image_height, BufferedImage.TYPE_3BYTE_BGR); ImageUtils.draw4on1(src_img, rez); ImageUtils.writeImage(rez, 1, dst); } catch (IOException ex) { logger.error("error while creating image for rubric; ", ex); succeed = false; } return succeed; }
From source file:com.db.comserv.main.utilities.HttpCaller.java
@Override @edu.umd.cs.findbugs.annotations.SuppressWarnings(value = "DM_DEFAULT_ENCODING") public HttpResult runRequest(String type, String methodType, URL url, List<Map<String, String>> headers, String requestBody, String sslByPassOption, int connTimeOut, int readTimeout, HttpServletRequest req) throws KeyManagementException, NoSuchAlgorithmException, KeyStoreException, UnsupportedEncodingException, IOException, UnknownHostException, URISyntaxException { StringBuffer response = new StringBuffer(); HttpResult httpResult = new HttpResult(); boolean gzip = false; final long startNano = System.nanoTime(); try {//from w w w.ja v a 2 s . c o m URL encodedUrl = new URL(Utility.encodeUrl(url.toString())); HttpURLConnection con = (HttpURLConnection) encodedUrl.openConnection(); TrustModifier.relaxHostChecking(con, sslByPassOption); // connection timeout 5s con.setConnectTimeout(connTimeOut); // read timeout 10s con.setReadTimeout(readTimeout * getQueryCost(req)); methodType = methodType.toUpperCase(); con.setRequestMethod(methodType); sLog.debug("Performing '{}' to '{}'", methodType, ServletUtil.filterUrl(url.toString())); // Get headers & set request property for (int i = 0; i < headers.size(); i++) { Map<String, String> header = headers.get(i); con.setRequestProperty(header.get("headerKey").toString(), header.get("headerValue").toString()); sLog.debug("Setting Header '{}' with value '{}'", header.get("headerKey").toString(), ServletUtil.filterHeaderValue(header.get("headerKey").toString(), header.get("headerValue").toString())); } if (con.getRequestProperty("Accept-Encoding") == null) { con.setRequestProperty("Accept-Encoding", "gzip"); } if (requestBody != null && !requestBody.equals("")) { con.setDoOutput(true); DataOutputStream wr = new DataOutputStream(con.getOutputStream()); wr.write(Utility.toUtf8Bytes(requestBody)); wr.flush(); wr.close(); } // push response BufferedReader in = null; String inputLine; List<String> contentEncoding = con.getHeaderFields().get("Content-Encoding"); if (contentEncoding != null) { for (String val : contentEncoding) { if ("gzip".equalsIgnoreCase(val)) { sLog.debug("Gzip enabled response"); gzip = true; break; } } } sLog.debug("Response: '{} {}' with headers '{}'", con.getResponseCode(), con.getResponseMessage(), ServletUtil.buildHeadersForLog(con.getHeaderFields())); if (con.getResponseCode() != 200 && con.getResponseCode() != 201) { if (con.getErrorStream() != null) { if (gzip) { in = new BufferedReader( new InputStreamReader(new GZIPInputStream(con.getErrorStream()), "UTF-8")); } else { in = new BufferedReader(new InputStreamReader(con.getErrorStream(), "UTF-8")); } } } else { String[] urlParts = url.toString().split("\\."); if (urlParts.length > 1) { String ext = urlParts[urlParts.length - 1]; if (ext.equalsIgnoreCase("png") || ext.equalsIgnoreCase("jpg") || ext.equalsIgnoreCase("jpeg") || ext.equalsIgnoreCase("gif")) { BufferedImage imBuff; if (gzip) { imBuff = ImageIO.read(new GZIPInputStream(con.getInputStream())); } else { BufferedInputStream bfs = new BufferedInputStream(con.getInputStream()); imBuff = ImageIO.read(bfs); } BufferedImage newImage = new BufferedImage(imBuff.getWidth(), imBuff.getHeight(), BufferedImage.TYPE_3BYTE_BGR); // converting image to greyScale int width = imBuff.getWidth(); int height = imBuff.getHeight(); for (int i = 0; i < height; i++) { for (int j = 0; j < width; j++) { Color c = new Color(imBuff.getRGB(j, i)); int red = (int) (c.getRed() * 0.21); int green = (int) (c.getGreen() * 0.72); int blue = (int) (c.getBlue() * 0.07); int sum = red + green + blue; Color newColor = new Color(sum, sum, sum); newImage.setRGB(j, i, newColor.getRGB()); } } ByteArrayOutputStream out = new ByteArrayOutputStream(); ImageIO.write(newImage, "jpg", out); byte[] bytes = out.toByteArray(); byte[] encodedBytes = Base64.encodeBase64(bytes); String base64Src = new String(encodedBytes); int imageSize = ((base64Src.length() * 3) / 4) / 1024; int initialImageSize = imageSize; int maxImageSize = Integer.parseInt(properties.getValue("Reduced_Image_Size")); float quality = 0.9f; if (!(imageSize <= maxImageSize)) { //This means that image size is greater and needs to be reduced. sLog.debug("Image size is greater than " + maxImageSize + " , compressing image."); while (!(imageSize < maxImageSize)) { base64Src = compress(base64Src, quality); imageSize = ((base64Src.length() * 3) / 4) / 1024; quality = quality - 0.1f; DecimalFormat df = new DecimalFormat("#.0"); quality = Float.parseFloat(df.format(quality)); if (quality <= 0.1) { break; } } } sLog.debug("Initial image size was : " + initialImageSize + " Final Image size is : " + imageSize + "Url is : " + url + "quality is :" + quality); String src = "data:image/" + urlParts[urlParts.length - 1] + ";base64," + new String(base64Src); JSONObject joResult = new JSONObject(); joResult.put("Image", src); out.close(); httpResult.setResponseCode(con.getResponseCode()); httpResult.setResponseHeader(con.getHeaderFields()); httpResult.setResponseBody(joResult.toString()); httpResult.setResponseMsg(con.getResponseMessage()); return httpResult; } } if (gzip) { in = new BufferedReader( new InputStreamReader(new GZIPInputStream(con.getInputStream()), "UTF-8")); } else { in = new BufferedReader(new InputStreamReader(con.getInputStream(), "UTF-8")); } } if (in != null) { while ((inputLine = in.readLine()) != null) { response.append(inputLine); } in.close(); } httpResult.setResponseCode(con.getResponseCode()); httpResult.setResponseHeader(con.getHeaderFields()); httpResult.setResponseBody(response.toString()); httpResult.setResponseMsg(con.getResponseMessage()); } catch (Exception e) { sLog.error("Failed to received HTTP response after timeout", e); httpResult.setTimeout(true); httpResult.setResponseCode(500); httpResult.setResponseMsg("Internal Server Error Timeout"); return httpResult; } return httpResult; }
From source file:fr.gael.drb.cortex.topic.sentinel3.jai.operator.QuicklookSlstrRIF.java
private BufferedImage toGrayScale(Raster in, PixelCorrection c, boolean invertColors, double lowerBound, double upperBound) { double offset = -lowerBound; double scaleFactor = 256. / (upperBound - lowerBound); int width = in.getWidth(); int height = in.getHeight(); // generate//from w ww. j av a 2 s. c om BufferedImage out = new BufferedImage(width, height, BufferedImage.TYPE_3BYTE_BGR); for (int j = 0; j < height; j++) { for (int i = 0; i < width; i++) { int pixel = checkAndApplyCorrection(in.getSample(i, j, 0), c); if (pixel == c.nodata) { if (invertColors) out.setRGB(i, j, new Color(255, 255, 255).getRGB()); else out.setRGB(i, j, new Color(0, 0, 0).getRGB()); continue; } double normalized = (pixel + offset) * scaleFactor; int gray = (int) (Math.max(0, Math.min(255, normalized))); if (invertColors) gray = 255 - gray; out.setRGB(i, j, new Color(gray, gray, gray).getRGB()); } } return out; }
From source file:com.xuggle.xuggler.UtilsTest.java
@SuppressWarnings("deprecation") @Test/*from w ww. j a v a 2s . c o m*/ public void testImageToImageSolidColor() { int w = 50; int h = 50; int gray = Color.GRAY.getRGB(); // construct an all gray image BufferedImage image1 = new BufferedImage(w, h, BufferedImage.TYPE_3BYTE_BGR); for (int x = 0; x < w; ++x) for (int y = 0; y < h; ++y) image1.setRGB(x, y, gray); // convert image1 to a picture and then back to image2 BufferedImage image2 = Utils.videoPictureToImage(Utils.imageToVideoPicture(image1, 0)); // test that all the pixels in image2 are gray, but not black or // white for (int x = 0; x < w; ++x) for (int y = 0; y < h; ++y) { int pixel = image2.getRGB(x, y); assertTrue("color value missmatch", pixel == gray); } }
From source file:common.utils.ImageUtils.java
/** * resize input image to new dinesions(only smaller) into rez parameter * @param image input image for scaling * @param rez resulting image. must have required width and height * @throws IOException/*from w w w.j ava2s. co m*/ */ public static void getScaledImageDimmension(BufferedImage image, int new_width, int new_height, OutputStream rez) throws IOException { BufferedImage dst = new BufferedImage(new_width, new_height, BufferedImage.TYPE_3BYTE_BGR); getScaledImageDimmension(image, dst); writeImage(dst, 1, rez); }