List of usage examples for java.awt.image BufferedImage getRGB
public int getRGB(int x, int y)
From source file:org.kurento.test.base.BrowserTest.java
public String ocr(BufferedImage imgBuff) { String parsedOut = null;//from w w w . j av a 2 s .c o m try { // Color image to pure black and white for (int x = 0; x < imgBuff.getWidth(); x++) { for (int y = 0; y < imgBuff.getHeight(); y++) { Color color = new Color(imgBuff.getRGB(x, y)); int red = color.getRed(); int green = color.getBlue(); int blue = color.getGreen(); if (red + green + blue > OCR_COLOR_THRESHOLD) { red = green = blue = 0; // Black } else { red = green = blue = 255; // White } Color col = new Color(red, green, blue); imgBuff.setRGB(x, y, col.getRGB()); } } // OCR recognition ByteArrayOutputStream baos = new ByteArrayOutputStream(); ImageIO.write(imgBuff, "png", baos); byte[] imageBytes = baos.toByteArray(); TessBaseAPI api = new TessBaseAPI(); api.Init(null, "eng"); ByteBuffer imgBB = ByteBuffer.wrap(imageBytes); PIX image = pixReadMem(imgBB, imageBytes.length); api.SetImage(image); // Get OCR result BytePointer outText = api.GetUTF8Text(); // Destroy used object and release memory api.End(); api.close(); outText.deallocate(); pixDestroy(image); // OCR corrections parsedOut = outText.getString().replaceAll("l", "1").replaceAll("Z", "2").replaceAll("O", "0") .replaceAll("B", "8").replaceAll("G", "6").replaceAll("S", "8").replaceAll("'", "") .replaceAll("", "").replaceAll("\\.", ":").replaceAll("E", "8").replaceAll("o", "0") .replaceAll("", "0").replaceAll("?", "6").replaceAll("", "5").replaceAll("I", "1") .replaceAll("T", "7").replaceAll("", "").replaceAll("U", "0").replaceAll("D", "0"); if (parsedOut.length() > 7) { parsedOut = parsedOut.substring(0, 7) + ":" + parsedOut.substring(8, parsedOut.length()); } parsedOut = parsedOut.replaceAll("::", ":"); // Remove last part (number of frames) int iSpace = parsedOut.lastIndexOf(" "); if (iSpace != -1) { parsedOut = parsedOut.substring(0, iSpace); } } catch (IOException e) { log.warn("IOException in OCR", e); } return parsedOut; }
From source file:org.opencastproject.videosegmenter.impl.jmf.ImageComparator.java
/** * Returns <code>true</code> if <code>image</code> differs from <code>currentImage</code>. In order to be treated a * different image, the <code>rgb</code> values of at least <code>changesThreshold</code> pixels must have changed. * <p>/*from w w w .j ava2s.c om*/ * Note that <code>image</code> might contain an altered version of the image, which will facilitate in the comparison * next time when <code>image</code> is <code>currentImage</code>. * * @param previousImage * the previous image * @param image * the new image * @param timestamp * the image timestamp * * @return <code>true</code> if the two images are different */ public boolean isDifferent(BufferedImage previousImage, BufferedImage image, long timestamp) { boolean differsFromCurrentScene = false; BufferedImage edgeImage = getEdgedImage(image); if (previousImage == null) { differsFromCurrentScene = true; logger.debug("First segment started"); } else if (previousImage.getWidth() != image.getWidth() || previousImage.getHeight() != image.getHeight()) { differsFromCurrentScene = true; String currentResolution = previousImage.getWidth() + "x" + previousImage.getHeight(); String newResolution = image.getWidth() + "x" + image.getHeight(); logger.warn("Resolution change detected ({} -> {})", currentResolution, newResolution); } else { int changes = 0; long pixels = image.getWidth() * image.getHeight(); long changesThresholdPixels = (long) (pixels * changesThreshold); imagecomparison: for (int x = 0; x < image.getWidth(); x++) { for (int y = 0; y < image.getHeight(); y++) { if (edgeImage.getRGB(x, y) != previousImage.getRGB(x, y)) { changes++; if (changes > changesThresholdPixels) { differsFromCurrentScene = true; if (!collectStatistics) break imagecomparison; } } } } float percentage = ((float) changes) / ((float) pixels); if (differsFromCurrentScene) logger.debug("Differences found at {} s ({} change to previous image)", timestamp, percentageNf.format(percentage)); else logger.debug("Found {} changes at {} s to the previous frame", percentageNf.format(percentage), timestamp); comparisons++; totalChanges += percentage; } // Write the images to disk for debugging and verification purposes if (tempDir != null) { try { FileUtils.forceMkdir(tempDir); ImageIO.write(image, "jpg", new File(tempDir, "image-" + timestamp + ".jpg")); ImageIO.write(edgeImage, "jpg", new File(tempDir, "image-" + timestamp + "-edged.jpg")); } catch (IOException e) { logger.warn("Error writing intermediary images to {}" + tempDir); e.printStackTrace(); } } // Copy the resulting image for further reference to the original image.getRaster().setRect(edgeImage.getData()); return differsFromCurrentScene; }
From source file:org.jtalks.jcommune.service.nontransactional.ImageConverter.java
/** * Creates a <code>BufferedImage</code> from an <code>Image</code>. This method can * function on a completely headless system. This especially includes Linux and Unix systems * that do not have the X11 libraries installed, which are required for the AWT subsystem to * operate. The resulting image will be smoothly scaled using bilinear filtering. * * @param source The image to convert * @param width The desired image width * @param height The desired image height * @param imageType int code RGB or ARGB * @return bufferedImage The resized image *///from w w w . j a v a2s . c o m private BufferedImage createBufferedImage(BufferedImage source, int imageType, int width, int height) { BufferedImage bufferedImage = new BufferedImage(width, height, imageType); int sourceX; int sourceY; double scaleX = (double) width / source.getWidth(); double scaleY = (double) height / source.getHeight(); int x1; int y1; double xDiff; double yDiff; int rgb; int rgb1; int rgb2; for (int y = 0; y < height; y++) { sourceY = y * source.getHeight() / bufferedImage.getHeight(); yDiff = y / scaleY - sourceY; for (int x = 0; x < width; x++) { sourceX = x * source.getWidth() / bufferedImage.getWidth(); xDiff = x / scaleX - sourceX; x1 = Math.min(source.getWidth() - 1, sourceX + 1); y1 = Math.min(source.getHeight() - 1, sourceY + 1); rgb1 = getRGBInterpolation(source.getRGB(sourceX, sourceY), source.getRGB(x1, sourceY), xDiff); rgb2 = getRGBInterpolation(source.getRGB(sourceX, y1), source.getRGB(x1, y1), xDiff); rgb = getRGBInterpolation(rgb1, rgb2, yDiff); bufferedImage.setRGB(x, y, rgb); } } return bufferedImage; }
From source file:io.bci.BitcoinSTLGenerator.java
private static void drawSTL(File qrFile, String filename) { int height = 0; int width = 0; float PLATFORM_RATIO = 2.3f; float PLATFORM_HEIGHT = 1.0f; boolean printPlatform = false; boolean printQRbottom = true; STLDrawer drawer = null;//from w ww .j a v a2s . c o m float[] pofloat1 = new float[3]; float[] pofloat2 = new float[3]; float[] pofloat3 = new float[3]; float[] pofloat4 = new float[3]; Color color; int count; BufferedImage image = null; try { drawer = new STLDrawer("STLs/" + filename + ".stl"); } catch (FileNotFoundException e) { System.out.println("ERROR: Unable to create stl file! - " + filename + ".stl"); e.printStackTrace(); } try { image = javax.imageio.ImageIO.read(qrFile); height = image.getHeight(); width = image.getWidth(); } catch (IOException e) { System.out.println("ERROR: Unable to open picture file! - " + qrFile.toString()); e.printStackTrace(); } if (printPlatform) { //Base background pofloat1[0] = 0.0f; pofloat1[1] = 0.0f; pofloat1[2] = 0; pofloat2[0] = 0.0f + (float) width; pofloat2[1] = 0.0f + 0.0f; pofloat2[2] = 0; pofloat3[0] = 0.0f + (float) width; pofloat3[1] = 0.0f + (float) height; pofloat3[2] = 0; pofloat4[0] = 0.0f + 0.0f; pofloat4[1] = 0.0f + (float) height; pofloat4[2] = 0; drawer.drawCube(pofloat1, pofloat2, pofloat3, pofloat4, PLATFORM_HEIGHT); //end base background } int[][] drawArray = new int[width + 2][height + 2]; for (int jj = 0; jj < height; jj++) { for (int ii = 0; ii < width; ii++) { color = new Color(image.getRGB(ii, jj)); if (color.equals(Color.BLACK)) { drawArray[ii + 1][height - jj + 1] = 1; //PNG origin starts at top left of image, my origin is bottom left } } } count = 0; for (int jj = 1; jj < height + 2; jj++) //drawTop { for (int ii = 1; ii < width + 2; ii++) { if (drawArray[ii][jj] == 1) { while ((ii + count < width + 2) && (drawArray[ii + count][jj] == 1) && (drawArray[ii + count][jj + 1] == 0)) { count++; } pofloat1[0] = (float) ii; pofloat1[1] = (float) jj; pofloat1[2] = PLATFORM_HEIGHT; pofloat4[0] = (float) ii + 0.0f; pofloat4[1] = (float) jj + 1.0f; pofloat4[2] = PLATFORM_HEIGHT; pofloat3[0] = (float) ii + count;//1.0f; pofloat3[1] = (float) jj + 1.0f; pofloat3[2] = PLATFORM_HEIGHT; pofloat2[0] = (float) ii + 1.0f; pofloat2[1] = (float) jj + 0.0f; pofloat2[2] = PLATFORM_HEIGHT; ii = ii + count; if (count != 0) { drawer.drawTop(pofloat1, pofloat2, pofloat3, pofloat4, PLATFORM_RATIO); } count = 0; } } } count = 0; for (int jj = 1; jj < height + 2; jj++) //bottom { for (int ii = 1; ii < width + 2; ii++) { if (drawArray[ii][jj] == 1) { while ((ii + count < width + 2) && (drawArray[ii + count][jj] == 1) && (drawArray[ii + count][jj - 1] == 0)) { count++; } pofloat1[0] = (float) ii; pofloat1[1] = (float) jj; pofloat1[2] = PLATFORM_HEIGHT; pofloat4[0] = (float) ii + 0.0f; pofloat4[1] = (float) jj + 1.0f; pofloat4[2] = PLATFORM_HEIGHT; pofloat3[0] = (float) ii + 1.0f; pofloat3[1] = (float) jj + 1.0f; pofloat3[2] = PLATFORM_HEIGHT; pofloat2[0] = (float) ii + count;//1.0f; pofloat2[1] = (float) jj + 0.0f; pofloat2[2] = PLATFORM_HEIGHT; if (count != 0) { drawer.drawBottom(pofloat1, pofloat2, pofloat3, pofloat4, PLATFORM_RATIO); } ii = ii + count; count = 0; } } } for (int ii = 1; ii < width + 2; ii++) //draw right { for (int jj = 1; jj < height + 2; jj++) { if (drawArray[ii][jj] == 1) { while ((jj + count < height + 2) && (drawArray[ii][jj + count] == 1) && (drawArray[ii + 1][jj + count] == 0)) { count++; } pofloat1[0] = (float) ii; pofloat1[1] = (float) jj; pofloat1[2] = PLATFORM_HEIGHT; pofloat4[0] = (float) ii + 0.0f; pofloat4[1] = (float) jj + 1.0f; pofloat4[2] = PLATFORM_HEIGHT; pofloat3[0] = (float) ii + 1.0f; pofloat3[1] = (float) jj + count;//1.0f; pofloat3[2] = PLATFORM_HEIGHT; pofloat2[0] = (float) ii + 1.0f; pofloat2[1] = (float) jj + 0.0f; pofloat2[2] = PLATFORM_HEIGHT; if (count != 0) { drawer.drawRight(pofloat1, pofloat2, pofloat3, pofloat4, PLATFORM_RATIO); } jj = jj + count; count = 0; } } } for (int ii = 1; ii < width + 2; ii++) //draw left { for (int jj = 1; jj < height + 2; jj++) { if (drawArray[ii][jj] == 1) { while ((jj + count < height + 2) && (drawArray[ii][jj + count] == 1) && (drawArray[ii - 1][jj + count] == 0)) { count++; } pofloat1[0] = (float) ii; pofloat1[1] = (float) jj; pofloat1[2] = PLATFORM_HEIGHT; pofloat4[0] = (float) ii + 0.0f; pofloat4[1] = (float) jj + count;//1.0f; pofloat4[2] = PLATFORM_HEIGHT; pofloat3[0] = (float) ii + 1.0f; pofloat3[1] = (float) jj + 1.0f; pofloat3[2] = PLATFORM_HEIGHT; pofloat2[0] = (float) ii + 1.0f; pofloat2[1] = (float) jj + 0.0f; pofloat2[2] = PLATFORM_HEIGHT; if (count != 0) { drawer.drawLeft(pofloat1, pofloat2, pofloat3, pofloat4, PLATFORM_RATIO); } jj = jj + count; count = 0; } } } for (int jj = 1; jj < height + 2; jj++) //draw back { for (int ii = 1; ii < width + 2; ii++) { if (drawArray[ii][jj] == 1) { while ((ii + count < width + 2) && (drawArray[ii + count][jj] == 1)) { count++; } pofloat1[0] = (float) ii; pofloat1[1] = (float) jj; pofloat1[2] = PLATFORM_HEIGHT; pofloat4[0] = (float) ii + 0.0f; pofloat4[1] = (float) jj + 1.0f; pofloat4[2] = PLATFORM_HEIGHT; pofloat3[0] = (float) ii + count;//1.0f; pofloat3[1] = (float) jj + 1.0f; pofloat3[2] = PLATFORM_HEIGHT; pofloat2[0] = (float) ii + count;//1.0f; pofloat2[1] = (float) jj + 0.0f; pofloat2[2] = PLATFORM_HEIGHT; if (count != 0) { drawer.drawBack(pofloat1, pofloat2, pofloat3, pofloat4, PLATFORM_RATIO); } ii = ii + count; count = 0; } } } if (printQRbottom) { for (int jj = 1; jj < height + 2; jj++) //draw front { for (int ii = 1; ii < width + 2; ii++) { if (drawArray[ii][jj] == 1) { while ((ii + count < width + 2) && (drawArray[ii + count][jj] == 1)) { count++; } pofloat1[0] = (float) ii; pofloat1[1] = (float) jj; pofloat1[2] = PLATFORM_HEIGHT; pofloat4[0] = (float) ii + 0.0f; pofloat4[1] = (float) jj + 1.0f; pofloat4[2] = PLATFORM_HEIGHT; pofloat3[0] = (float) ii + count;//1.0f; pofloat3[1] = (float) jj + 1.0f; pofloat3[2] = PLATFORM_HEIGHT; pofloat2[0] = (float) ii + count;//1.0f; pofloat2[1] = (float) jj + 0.0f; pofloat2[2] = PLATFORM_HEIGHT; if (count != 0) { drawer.drawFront(pofloat1, pofloat2, pofloat3, pofloat4, PLATFORM_RATIO); } ii = ii + count; count = 0; } } } } drawer.resizeNumTriangles(); System.out.println("STL drawn: " + filename + ".stl"); drawer.closeFile(); }
From source file:org.pentaho.di.core.gui.SwingDirectGC.java
private void drawImage(SwingUniversalImage img, int locationX, int locationY, int imageSize) { if (isDrawingPixelatedImages() && img.isBitmap()) { BufferedImage bi = new BufferedImage(imageSize, imageSize, BufferedImage.TYPE_INT_ARGB); Graphics2D g2 = (Graphics2D) bi.getGraphics(); g2.setColor(Color.WHITE); g2.fillRect(0, 0, imageSize, imageSize); g2.drawImage(img.getAsBitmapForSize(imageSize, imageSize), 0, 0, observer); g2.dispose();/* w ww.j a va2s. c o m*/ for (int x = 0; x < bi.getWidth(observer); x++) { for (int y = 0; y < bi.getHeight(observer); y++) { int rgb = bi.getRGB(x, y); gc.setColor(new Color(rgb)); gc.setStroke(new BasicStroke(1.0f)); gc.drawLine(locationX + xOffset + x, locationY + yOffset + y, locationX + xOffset + x, locationY + yOffset + y); } } } else { gc.setBackground(Color.white); gc.clearRect(locationX, locationY, imageSize, imageSize); img.drawToGraphics(gc, locationX, locationY, imageSize, imageSize); } }
From source file:playground.christoph.evacuation.analysis.EvacuationTimePictureWriter.java
private ScreenOverlayType createHistogram(String transportMode, Map<Id, Double> evacuationTimes) throws IOException { /*//from w w w. j av a 2s.c o m * Remove NaN entries from the List */ List<Double> listWithoutNaN = new ArrayList<Double>(); for (Double d : evacuationTimes.values()) if (!d.isNaN()) listWithoutNaN.add(d); /* * If trip with significant to high evacuation times should be cut off */ if (limitMaxEvacuationTime) { double cutOffValue = meanEvacuationTime + standardDeviation * evacuationTimeCutOffFactor; ListIterator<Double> iter = listWithoutNaN.listIterator(); while (iter.hasNext()) { double value = iter.next(); if (value > cutOffValue) iter.remove(); } } double[] array = new double[listWithoutNaN.size()]; int i = 0; for (double d : listWithoutNaN) array[i++] = d; JFreeChart chart = createHistogramChart(transportMode, array); BufferedImage chartImage = chart.createBufferedImage(OVERALLHISTOGRAMWIDTH, OVERALLHISTOGRAMHEIGHT); BufferedImage image = new BufferedImage(OVERALLHISTOGRAMWIDTH, OVERALLHISTOGRAMHEIGHT, BufferedImage.TYPE_4BYTE_ABGR); // clone image and set alpha value for (int x = 0; x < OVERALLHISTOGRAMWIDTH; x++) { for (int y = 0; y < OVERALLHISTOGRAMHEIGHT; y++) { int rgb = chartImage.getRGB(x, y); Color c = new Color(rgb); int r = c.getRed(); int b = c.getBlue(); int g = c.getGreen(); int argb = 225 << 24 | r << 16 | g << 8 | b; // 225 as transparency value image.setRGB(x, y, argb); } } byte[] imageBytes = bufferedImageToByteArray(image); this.kmzWriter.addNonKMLFile(imageBytes, transportMode + OVERALLHISTROGRAM); ScreenOverlayType overlay = kmlObjectFactory.createScreenOverlayType(); LinkType icon = kmlObjectFactory.createLinkType(); icon.setHref(transportMode + OVERALLHISTROGRAM); overlay.setIcon(icon); overlay.setName("Histogram " + transportMode); // place the image top right Vec2Type overlayXY = kmlObjectFactory.createVec2Type(); overlayXY.setX(0.0); overlayXY.setY(1.0); overlayXY.setXunits(UnitsEnumType.FRACTION); overlayXY.setYunits(UnitsEnumType.FRACTION); overlay.setOverlayXY(overlayXY); Vec2Type screenXY = kmlObjectFactory.createVec2Type(); screenXY.setX(0.02); screenXY.setY(0.98); screenXY.setXunits(UnitsEnumType.FRACTION); screenXY.setYunits(UnitsEnumType.FRACTION); overlay.setScreenXY(screenXY); return overlay; }
From source file:Trabalho.HistogramaHSB.java
public ChartPanel criaHistograma() throws IOException { //pega a imagem BufferedImage img = pegaImagem(); //w pega a largura da imagem - h pega a altura da imagem int w = img.getWidth(); int h = img.getHeight(); //d calcula o tamanho da imagem int d = (w * h); //red, green e blue iro receber os tons de cor antigo da imagem - u vai receber o RGB da cor int red, green, blue, u; //retorna rgb no mtodo float[] hsb;//from w w w. j a v a 2 s . c o m int[] vetH = new int[256]; int[] vetS = new int[256]; int[] vetB = new int[256]; float hue, sat, bri; //cAux e oldColor pegam os tons originais da imagem - newColor pega os tons aps o clculo Color oldColor; Color newColor; //for responsvel por substituir os tons antigos pelos novos; percorrem a imagem por largura e altura for (int i = 0; i < w; i++) { for (int j = 0; j < h; j++) { u = img.getRGB(i, j); //u vai receber o RGB da posio i, j oldColor = new Color(u); //oldColor instanciado e recebe o valor de u //cada cor recebe o valor do tom original red = oldColor.getRed(); green = oldColor.getGreen(); blue = oldColor.getBlue(); hsb = Color.RGBtoHSB(red, green, blue, null); hue = hsb[0]; sat = hsb[1]; bri = hsb[2]; // System.out.println("RGB [" + red + "," + green + "," + blue + "] converted to HSB [" + hue + "," + sat + "," + bri + "]"); // hue = hue * 360; // int convH = Integer.valueOf(new Float(hue).intValue()); // vetH[convH]++; // // sat = sat * 100; // int convS = Integer.valueOf(new Float(sat).intValue()); // vetS[convS]++; // // bri = bri * 100; // int convB = Integer.valueOf(new Float(bri).intValue()); // vetB[convB]++; newColor = new Color(hue, sat, bri); //seta o RGB da imagem nas posies i, j pegando os valores da newColor img.setRGB(i, j, newColor.getRGB()); } } File ouptut = new File("D:\\ProjetosNetBeans\\PDI\\src\\imagens\\5.jpeg"); ImageIO.write(img, "png", ouptut); dataset = new HistogramDataset(); //pega o RGB r = raster.getSamples(0, 0, w, h, 0, r); dataset.addSeries("Red", r, 360); r = raster.getSamples(0, 0, w, h, 1, r); dataset.addSeries("Green", r, 101); r = raster.getSamples(0, 0, w, h, 2, r); dataset.addSeries("Blue", r, 101); JFreeChart chart = ChartFactory.createHistogram("Histograma", "Pixels", "Y", dataset, PlotOrientation.VERTICAL, true, true, false); //Plota as cores XYPlot plot = (XYPlot) chart.getPlot(); renderer = (XYBarRenderer) plot.getRenderer(); renderer.setBarPainter(new StandardXYBarPainter()); //vermelho, verde, azul Paint[] paintArray = { new Color(0x80ff0000, true), new Color(0x8000ff00, true), new Color(0x800000ff, true) }; //desenhando o grfico plot.setDrawingSupplier( new DefaultDrawingSupplier(paintArray, DefaultDrawingSupplier.DEFAULT_FILL_PAINT_SEQUENCE, DefaultDrawingSupplier.DEFAULT_OUTLINE_PAINT_SEQUENCE, DefaultDrawingSupplier.DEFAULT_STROKE_SEQUENCE, DefaultDrawingSupplier.DEFAULT_OUTLINE_STROKE_SEQUENCE, DefaultDrawingSupplier.DEFAULT_SHAPE_SEQUENCE)); ChartPanel panel = new ChartPanel(chart); panel.setMouseWheelEnabled(true); return panel; }
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 {// w w w .j a v a2s .co 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:de._13ducks.cor.graphics.GraphicsComponent.java
protected void calcColoredMaps(Color[] colors) { // Berechnet die eingefrbten Texturen, z.B. fr Gebude ArrayList<CoRImage> tList = new ArrayList<CoRImage>(); tList.addAll(coloredImgMap.values()); coloredImgMap.clear();//from ww w . j a v a2s . c o m for (int i = 0; i < tList.size(); i++) { BufferedImage im = (BufferedImage) tList.get(i).getImage(); for (int playerId = 0; playerId < colors.length; playerId++) { BufferedImage preImg = new BufferedImage(im.getWidth(), im.getHeight(), BufferedImage.TYPE_INT_ARGB); for (int x = 0; x < im.getWidth(); x++) { for (int y = 0; y < im.getHeight(); y++) { // Das ganze Raster durchgehen und Farben ersetzen // Ersetzfarbe da? int rgb = im.getRGB(x, y); float[] col = Color.RGBtoHSB((rgb >> 16) & 0xff, (rgb >> 8) & 0xff, rgb & 0xff, null); if (col[0] >= 0.8583333f && col[0] <= 0.8666666f) { // Ja, ersetzen Color tc = colors[playerId]; int targetC = Color.HSBtoRGB( Color.RGBtoHSB(tc.getRed(), tc.getGreen(), tc.getBlue(), null)[0], 1.0f, col[2]); int a = (rgb >> 24) & 0xff; targetC = (targetC & (~(0xff << 24)) | (a << 24)); preImg.setRGB(x, y, targetC); } else { preImg.setRGB(x, y, im.getRGB(x, y)); } } } // Bild berechnet, einfgen CoRImage newImg = new CoRImage(preImg); newImg.setImageName(tList.get(i).getImageName()); coloredImgMap.put(newImg.getImageName() + playerId, newImg); } } }
From source file:com.tomtom.speedtools.json.JsonTest.java
/** * Mix-in annotations for Jackson./* w w w . ja v a 2 s . c o m*/ */ @Test public void testImageMixIn() throws Exception { LOG.info("testImageMixIn"); @SuppressWarnings("IOResourceOpenedButNotSafelyClosed") final BufferedImage image1 = ImageIO.read(this.getClass().getResourceAsStream("jsontest.png")); LOG.info("image = {}", image1); final String json2 = Json.toJson(image1); LOG.info("image.toJson = {}", json2); Assert.assertTrue(json2.startsWith("\"iVBORw0KGgoAAAANSUhEUgAAALwAAAAbCAYAAADGUOX9AAAOZ0lEQVR42u2c")); Assert.assertTrue(json2.endsWith("IIug/T0xKHk+QOxoDXaf/AeOQWjzHxhS4AAAAAElFTkSuQmCC\"")); final BufferedImage image2 = Json.fromJson(json2, BufferedImage.class); Assert.assertNotNull(image2); Assert.assertEquals(image1.getHeight(), image2.getHeight()); Assert.assertEquals(image1.getWidth(), image2.getWidth()); for (int x = 0; x < image1.getWidth(); ++x) { for (int y = 0; y < image1.getHeight(); ++y) { Assert.assertEquals(image1.getRGB(x, y), image2.getRGB(x, y)); } } }