List of usage examples for java.awt Color getRGB
public int getRGB()
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 ww . ja v a2 s.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:org.geoserver.wms.WMSTestSupport.java
/** * Counts the number of non black pixels * /*from w w w . java 2s . c o m*/ * @param testName * @param image * @param bgColor * @return */ protected int countNonBlankPixels(String testName, BufferedImage image, Color bgColor) { int pixelsDiffer = 0; for (int y = 0; y < image.getHeight(); y++) { for (int x = 0; x < image.getWidth(); x++) { if (image.getRGB(x, y) != bgColor.getRGB()) { ++pixelsDiffer; } } } LOGGER.fine(testName + ": pixel count=" + (image.getWidth() * image.getHeight()) + " non bg pixels: " + pixelsDiffer); return pixelsDiffer; }
From source file:com.offbynull.peernetic.debug.visualizer.JGraphXVisualizer.java
private void changeNode(final ChangeNodeCommand<A> command) { Validate.notNull(command);//from w w w .j a v a 2s . co m SwingUtilities.invokeLater(() -> { A address = command.getNode(); Object vertex = nodeLookupMap.get(address); Validate.isTrue(vertex != null); Point center = command.getLocation(); if (center != null) { mxRectangle rect = graph.getView().getBoundingBox(new Object[] { vertex }); graph.moveCells(new Object[] { vertex }, center.getX() - rect.getCenterX(), center.getY() - rect.getCenterY()); } Double scale = command.getScale(); if (scale != null) { mxGraphView view = graph.getView(); mxRectangle rect = graph.getBoundingBox(vertex); rect.setWidth(rect.getWidth() / view.getScale() * scale); rect.setHeight(rect.getHeight() / view.getScale() * scale); rect.setX(rect.getX() / view.getScale()); rect.setY(rect.getY() / view.getScale()); graph.resizeCell(vertex, rect); } Color color = command.getColor(); if (color != null) { graph.setCellStyle(mxConstants.STYLE_FILLCOLOR + "=" + "#" + String.format("%06x", color.getRGB() & 0x00FFFFFF), new Object[] { vertex }); nodeLookupMap.put(address, vertex); } zoomFit(); }); }
From source file:pack1.test.java
@WebMethod(operationName = "convert") public String convert(@WebParam(name = "encodedImageStr") String encodedImageStr, @WebParam(name = "fileName") String fileName, @WebParam(name = "AOR") String AOR, @WebParam(name = "val") int value) { System.out.println("Value" + value); FileOutputStream imageOutFile = null; try {/*from ww w. java 2 s. c om*/ Connection con, con1; Statement stmtnew = null; area = Double.parseDouble(AOR); //int val=Integer.parseInt(value); System.out.println("connecting"); Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); System.out.println("connected"); con = DriverManager.getConnection("jdbc:odbc:test"); System.out.println(" driver loaded in connection.jsp"); stmtnew = con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE); // Decode String using Base64 Class byte[] imageByteArray = encodedImageStr.getBytes(); // Write Image into File system - Make sure you update the path imageOutFile = new FileOutputStream( "C:/Users/Kushagr Jolly/Documents/NetBeansProjects/webservice/IASRI/cropped" + fileName); imageOutFile.write(imageByteArray); imageOutFile.close(); System.out.println("Image Successfully Stored"); FileInputStream leafPicPath = new FileInputStream( "C:/Users/Kushagr Jolly/Documents/NetBeansProjects/webservice/IASRI/cropped" + fileName); BufferedImage cat; int height, width; cat = ImageIO.read(leafPicPath); height = cat.getHeight(); width = cat.getWidth(); for (int w = 0; w < cat.getWidth(); w++) { for (int h = 0; h < cat.getHeight(); h++) { // BufferedImage.getRGB() saves the colour of the pixel as a single integer. // use Color(int) to grab the RGB values individually. Color color = new Color(cat.getRGB(w, h)); // use the RGB values to get their average. int averageColor = ((color.getRed() + color.getGreen() + color.getBlue()) / 3); // create a new Color object using the average colour as the red, green and blue // colour values Color avg = new Color(averageColor, averageColor, averageColor); // set the pixel at that position to the new Color object using Color.getRGB(). cat.setRGB(w, h, avg.getRGB()); } } String greyPicPath = "C:/Users/Kushagr Jolly/Documents/NetBeansProjects/webservice/IASRI/greyscale" + fileName; greyPicPath = greyPicPath.trim(); File outputfile = new File(greyPicPath); ImageIO.write(cat, "jpg", outputfile); System.out.println("Image is successfully converted to grayscale"); String binPicPath = "C:/Users/Kushagr Jolly/Documents/NetBeansProjects/webservice/IASRI/binary" + fileName; File f2 = new File(binPicPath); System.out.println("1"); ImageProcessor ip; ImagePlus imp = new ImagePlus(greyPicPath); System.out.println("2"); ip = imp.getProcessor(); ip.invertLut(); ip.autoThreshold(); System.out.println("3"); BufferedImage bf = ip.getBufferedImage(); System.out.println("4"); ImageIO.write(bf, "jpg", f2); System.out.println("Image is successfully converted to binary image"); if (choice == 1) { String Inserted1 = "insert into test (PhyAOR) values ('" + area + "')"; System.out.println("InsertedQuery" + Inserted1); stmtnew.executeUpdate(Inserted1); Statement stmt = con.createStatement(); ResultSet rs = null; String ID = "select MAX(id) as id from test"; System.out.println("Query" + ID); rs = stmt.executeQuery(ID); while (rs.next()) { id = rs.getInt("id"); } String Inserted2 = "update test set fileName0=? where id=?"; PreparedStatement ps = con.prepareStatement(Inserted2); ps.setString(1, fileName); ps.setDouble(2, id); int rt = ps.executeUpdate(); choice++; } System.out.println(choice); if (value == 1) { int count = countblackpixel(binPicPath); calculatepixA(count, area); //returnVal=value+"/"+count+"/"+OnepixArea; } else if (value == 2) { int flag = countblackpixel(binPicPath); // calculatepixA(flag, area); leafarea0(flag, area); //returnVal=value+"/"+flag+"/"+OnepixArea+"/"+leafArea0; //System.out.println(returnVal); } else if (value == 3) { String Inserted3 = "update test set fileName180=? where id=?"; PreparedStatement ps1 = con.prepareStatement(Inserted3); ps1.setString(1, fileName); ps1.setDouble(2, id); int rt = ps1.executeUpdate(); int black = countblackpixel(binPicPath); leafarea180(area, black); finalarea(); Statement stmt = con.createStatement(); ResultSet rs = null; String finalans = "select PhyAOR,onePixA,leafarea0,leafarea180,finalleafarea from test where id=" + id + ""; rs = stmt.executeQuery(finalans); while (rs.next()) { returnVal = rs.getString("PhyAOR") + "/" + rs.getString("onePixA") + "/" + rs.getString("leafarea0") + "/" + rs.getString("leafarea180") + "/" + rs.getString("finalleafarea"); } //returnVal=value+"/"+black+"/"+OnepixArea+"/"+leafArea180+"/"+Leaf_Area; } else if (value == 4) { finalarea(); } imageOutFile.close(); } catch (Exception ex) { Logger.getLogger(test.class.getName()).log(Level.SEVERE, null, ex); System.out.println(ex); } return returnVal; }
From source file:org.deegree.ogcwebservices.wms.dataaccess.ID2PInterpolation.java
private void insertValue(int x, int y, double val) { Iterator<double[]> keys = colorMap.keySet().iterator(); double[] d = keys.next(); Color color = null; while (!(val >= d[0] && val < d[1])) { d = keys.next();// www .ja va 2 s . c om } color = colorMap.get(d); try { image.setRGB(x, y, color.getRGB()); } catch (Exception e) { System.out.println(x + " " + y); } }
From source file:edu.stanford.epad.epadws.handlers.dicom.DSOUtil.java
private static Image makeColorTransparent(BufferedImage im, final Color color) { ImageFilter filter = new RGBImageFilter() { public int markerRGB = color.getRGB() | 0xFF000000; @Override//from w ww. j av a 2s.co m public final int filterRGB(int x, int y, int rgb) { if ((rgb | 0xFF000000) == markerRGB) { return 0x00FFFFFF & rgb; } else { return rgb; } } }; ImageProducer ip = new FilteredImageSource(im.getSource(), filter); return Toolkit.getDefaultToolkit().createImage(ip); }
From source file:ca.sqlpower.architect.swingui.TestPlayPen.java
/** * Returns a new value that is not equal to oldVal. The * returned object will be a new instance compatible with oldVal. * /*from ww w . ja v a 2 s.co m*/ * @param property The property that should be modified. * @param oldVal The existing value of the property to modify. The returned value * will not equal this one at the time this method was first called. */ private Object getNewDifferentValue(PropertyDescriptor property, Object oldVal) { Object newVal; // don't init here so compiler can warn if the // following code doesn't always give it a value if (property.getPropertyType() == String.class) { newVal = "new " + oldVal; } else if (property.getPropertyType() == Boolean.class || property.getPropertyType() == Boolean.TYPE) { if (oldVal == null) { newVal = new Boolean(false); } else { newVal = new Boolean(!((Boolean) oldVal).booleanValue()); } } else if (property.getPropertyType() == Double.class || property.getPropertyType() == Double.TYPE) { if (oldVal == null) { newVal = new Double(0); } else { newVal = new Double(((Double) oldVal).doubleValue() + 1); } } else if (property.getPropertyType() == Integer.class || property.getPropertyType() == Integer.TYPE) { if (oldVal == null) { newVal = new Integer(0); } else { newVal = new Integer(((Integer) oldVal).intValue() + 1); } } else if (property.getPropertyType() == Color.class) { if (oldVal == null) { newVal = new Color(0xFAC157); } else { Color oldColor = (Color) oldVal; newVal = new Color((oldColor.getRGB() + 0xF00) % 0x1000000); } } else if (property.getPropertyType() == Font.class) { if (oldVal == null) { newVal = FontManager.getDefaultPhysicalFont(); } else { Font oldFont = (Font) oldVal; newVal = new Font(oldFont.getFontName(), oldFont.getSize() + 2, oldFont.getStyle()); } } else if (property.getPropertyType() == Set.class) { newVal = new HashSet(); ((Set) newVal).add("test"); } else if (property.getPropertyType() == List.class) { newVal = new ArrayList(); ((List) newVal).add("test"); } else if (property.getPropertyType() == Point.class) { newVal = new Point(1, 3); } else { throw new RuntimeException("This test case lacks a value for " + property.getName() + " (type " + property.getPropertyType().getName() + ") in getNewDifferentValue()"); } return newVal; }
From source file:edu.stanford.epad.epadws.handlers.dicom.DSOUtil.java
private static Image makeColorOpaque(BufferedImage im, final Color color) { nonBlank.set(false);/* w w w .ja va 2s. c o m*/ ImageFilter filter = new RGBImageFilter() { public int markerRGB = color.getRGB() | 0xFF000000; @Override public final int filterRGB(int x, int y, int rgb) { if ((rgb & 0x00FFFFFF) != 0) { nonBlank.set(true); } if ((rgb | 0xFF000000) == markerRGB) { // nonBlank.set(true); return 0xFF000000 | rgb; } else { return rgb; } } }; ImageProducer ip = new FilteredImageSource(im.getSource(), filter); return Toolkit.getDefaultToolkit().createImage(ip); }
From source file:org.wings.plaf.css.Utils.java
public static String toColorString(java.awt.Color c) { return toColorString(c.getRGB()); }