List of usage examples for java.awt.image BufferedImage getWidth
public int getWidth()
From source file:org.jamwiki.servlets.UploadServlet.java
/** * @return ImageData object from uploaded binary data. *///from w w w . j a va 2 s .c o m private ImageData processImageData(String contentType, byte buff[]) { int width = -1; int height = -1; try { BufferedImage image = ImageIO.read(new ByteArrayInputStream(buff)); if (image != null) { width = image.getWidth(); height = image.getHeight(); } } catch (IOException e) { logger.info("Failure while processing image", e); } return new ImageData(contentType, width, height, buff); }
From source file:com.buddycloud.mediaserver.MediaServerTest.java
protected Media buildMedia(String mediaId, String filePath) throws Exception { File file = new File(filePath); String fileName = file.getName(); String extension = fileName.substring(fileName.indexOf(".") + 1); Media media = new Media(); media.setId(mediaId);//from w ww. jav a 2s. c o m media.setFileName(fileName); media.setEntityId(BASE_CHANNEL); media.setAuthor(BASE_USER); media.setDescription("A description"); media.setTitle("A title"); media.setFileSize(file.length()); media.setShaChecksum(getFileShaChecksum(file)); media.setFileExtension(extension); media.setMimeType(MimeTypeMapping.lookupMimeType(extension)); if (ImageUtils.isImage(extension)) { BufferedImage img = ImageIO.read(file); media.setHeight(img.getHeight()); media.setWidth(img.getWidth()); } else if (VideoUtils.isVideo(extension)) { VideoUtils videoUtils = new VideoUtils(file); media.setLength(videoUtils.getVideoLength()); media.setHeight(videoUtils.getVideoHeight()); media.setWidth(videoUtils.getVideoWidth()); } else if (AudioUtils.isAudio(extension)) { media.setLength(AudioUtils.getAudioLength(file)); } return media; }
From source file:ddf.catalog.transformer.OverlayMetacardTransformerTest.java
@Test public void testOverlayRotated() throws Exception { final MetacardImpl metacard = getMetacard(); metacard.setLocation("POLYGON ((0 1, 1 0, 0 -1, -1 0, 0 1))"); final BinaryContent content = transform(metacard, null); final BufferedImage originalImage = getImage(getImageBytes()); final BufferedImage overlayImage = getImage(content.getByteArray()); // We can only make these assertions because we are rotating a square image assertThat(overlayImage.getWidth(), greaterThan(originalImage.getHeight())); assertThat(overlayImage.getHeight(), greaterThan(originalImage.getHeight())); }
From source file:apiserver.services.images.services.jhlabs.MaskFilterService.java
public Object doFilter(Message<?> message) throws MessageConfigException { MaskJob props = (MaskJob) message.getPayload(); Object maskImage = props.getMask(); try {//from www.jav a 2s.c o m BufferedImage bufferedImage = props.getBufferedImage(); if (bufferedImage == null) { throw new MessageConfigException(MessageConfigException.MISSING_PROPERTY); } BufferedImage destImage = new BufferedImage(bufferedImage.getWidth(), bufferedImage.getHeight(), bufferedImage.getType()); //run filter ApplyMaskFilter filter = new ApplyMaskFilter(); filter.setDestination(destImage); filter.setMaskImage(bufferedImage); BufferedImage outFile = filter.filter(bufferedImage, null); props.setBufferedImage(outFile); return message; } catch (Throwable e) { //log.error(e.getMessage(), e); throw new RuntimeException(e); } }
From source file:de.ep3.ftpc.view.designer.UIDesigner.java
/** * Loads an icon image from the resources directory provided. * * The icon will be recolored according to the UI default color * (with respect to its alpha values)./*from w w w . j a v a2 s .c o m*/ * * @param dirName The directory name under the resource/drawable directory. * @param fileName The file name under the directory name provided before. * @return The icom ready to be displayed within the GUI. */ public Icon getDefaultIcon(String dirName, String fileName) { BufferedImage image = getDefaultImage(dirName, fileName); /* Change icon color according to UI color */ int imageHeight = image.getHeight(); int imageWidth = image.getWidth(); int defaultRGBA = getDefaultBorderColor().getRGB(); int defaultRGB = defaultRGBA & 0x00FFFFFF; for (int y = 0; y < imageHeight; y++) { for (int x = 0; x < imageWidth; x++) { int imageRGBA = image.getRGB(x, y); int imageA = imageRGBA & 0xFF000000; int newRGBA = defaultRGB | imageA; // I'm quite proud of this little bitwise color calculation ^-^ image.setRGB(x, y, newRGBA); } } return new ImageIcon(image); }
From source file:blusunrize.immersiveengineering.client.render.TileRenderAutoWorkbench.java
public static BlueprintLines getBlueprintDrawable(ItemStack stack, World world) { if (stack.isEmpty()) return null; EntityPlayer player = ClientUtils.mc().player; ArrayList<BufferedImage> images = new ArrayList<>(); try {//from w w w .j a va 2 s .c o m IBakedModel ibakedmodel = ClientUtils.mc().getRenderItem().getItemModelWithOverrides(stack, world, player); HashSet<String> textures = new HashSet(); Collection<BakedQuad> quads = ibakedmodel.getQuads(null, null, 0); for (BakedQuad quad : quads) if (quad != null && quad.getSprite() != null) textures.add(quad.getSprite().getIconName()); for (String s : textures) { ResourceLocation rl = new ResourceLocation(s); rl = new ResourceLocation(rl.getNamespace(), String.format("%s/%s%s", "textures", rl.getPath(), ".png")); IResource resource = ClientUtils.mc().getResourceManager().getResource(rl); BufferedImage bufferedImage = TextureUtil.readBufferedImage(resource.getInputStream()); if (bufferedImage != null) images.add(bufferedImage); } } catch (Exception e) { } if (images.isEmpty()) return null; ArrayList<Pair<TexturePoint, TexturePoint>> lines = new ArrayList(); HashSet testSet = new HashSet(); HashMultimap<Integer, TexturePoint> area = HashMultimap.create(); int wMax = 0; for (BufferedImage bufferedImage : images) { Set<Pair<TexturePoint, TexturePoint>> temp_lines = new HashSet<>(); int w = bufferedImage.getWidth(); int h = bufferedImage.getHeight(); if (h > w) h = w; if (w > wMax) wMax = w; for (int hh = 0; hh < h; hh++) for (int ww = 0; ww < w; ww++) { int argb = bufferedImage.getRGB(ww, hh); float r = (argb >> 16 & 255) / 255f; float g = (argb >> 8 & 255) / 255f; float b = (argb & 255) / 255f; float intesity = (r + b + g) / 3f; int alpha = (argb >> 24) & 255; if (alpha > 0) { boolean added = false; //Check colour sets for similar colour to shade it later TexturePoint tp = new TexturePoint(ww, hh, w); if (!testSet.contains(tp)) { for (Integer key : area.keySet()) { for (TexturePoint p : area.get(key)) { float mod = w / (float) p.scale; int pColour = bufferedImage.getRGB((int) (p.x * mod), (int) (p.y * mod)); float dR = (r - (pColour >> 16 & 255) / 255f); float dG = (g - (pColour >> 8 & 255) / 255f); float dB = (b - (pColour & 255) / 255f); double delta = Math.sqrt(dR * dR + dG * dG + dB * dB); if (delta < .25) { area.put(key, tp); added = true; break; } } if (added) break; } if (!added) area.put(argb, tp); testSet.add(tp); } //Compare to direct neighbour for (int i = 0; i < 4; i++) { int xx = (i == 0 ? -1 : i == 1 ? 1 : 0); int yy = (i == 2 ? -1 : i == 3 ? 1 : 0); int u = ww + xx; int v = hh + yy; int neighbour = 0; float delta = 1; boolean notTransparent = false; if (u >= 0 && u < w && v >= 0 && v < h) { neighbour = bufferedImage.getRGB(u, v); notTransparent = ((neighbour >> 24) & 255) > 0; if (notTransparent) { float neighbourIntesity = ((neighbour >> 16 & 255) + (neighbour >> 8 & 255) + (neighbour & 255)) / 765f; float intesityDelta = Math.max(0, Math.min(1, Math.abs(intesity - neighbourIntesity))); float rDelta = Math.max(0, Math.min(1, Math.abs(r - (neighbour >> 16 & 255) / 255f))); float gDelta = Math.max(0, Math.min(1, Math.abs(g - (neighbour >> 8 & 255) / 255f))); float bDelta = Math.max(0, Math.min(1, Math.abs(b - (neighbour & 255) / 255f))); delta = Math.max(intesityDelta, Math.max(rDelta, Math.max(gDelta, bDelta))); delta = delta < .25 ? 0 : delta > .4 ? 1 : delta; } } if (delta > 0) { Pair<TexturePoint, TexturePoint> l = Pair.of( new TexturePoint(ww + (i == 0 ? 0 : i == 1 ? 1 : 0), hh + (i == 2 ? 0 : i == 3 ? 1 : 0), w), new TexturePoint(ww + (i == 0 ? 0 : i == 1 ? 1 : 1), hh + (i == 2 ? 0 : i == 3 ? 1 : 1), w)); temp_lines.add(l); } } } } lines.addAll(temp_lines); } ArrayList<Integer> lumiSort = new ArrayList<>(area.keySet()); Collections.sort(lumiSort, (rgb1, rgb2) -> Double.compare(getLuminance(rgb1), getLuminance(rgb2))); HashMultimap<ShadeStyle, Point> complete_areaMap = HashMultimap.create(); int lineNumber = 2; int lineStyle = 0; for (Integer i : lumiSort) { complete_areaMap.putAll(new ShadeStyle(lineNumber, lineStyle), area.get(i)); ++lineStyle; lineStyle %= 3; if (lineStyle == 0) lineNumber += 1; } Set<Pair<Point, Point>> complete_lines = new HashSet<>(); for (Pair<TexturePoint, TexturePoint> line : lines) { TexturePoint p1 = line.getKey(); TexturePoint p2 = line.getValue(); complete_lines.add(Pair.of( new Point((int) (p1.x / (float) p1.scale * wMax), (int) (p1.y / (float) p1.scale * wMax)), new Point((int) (p2.x / (float) p2.scale * wMax), (int) (p2.y / (float) p2.scale * wMax)))); } return new BlueprintLines(wMax, complete_lines, complete_areaMap); }
From source file:com.github.pitzcarraldo.dissimilar.Dissimilar.java
/** * Compare two files, according to parameters passed via command line * @param pOne first file to compare//from w w w . j ava2 s .c om * @param pTwo second file to compare * @param pHeatMapImage file to save ssim heat map image to * @param pCalcSSIM whether or not to calculate ssim * @param pCalcPSNR whether or not to calculate psnr */ private static void compare(final File pOne, final File pTwo, final String pHeatMapImage, final boolean pCalcSSIM, final boolean pCalcPSNR) { //just load the images once and use the internal methods for calculating ssim/psnr long time = System.currentTimeMillis(); BufferedImage imageOne = null; try { imageOne = Imaging.getBufferedImage(pOne); } catch (IOException e) { printError(pOne, false, false, pTwo, false); return; } catch (NullPointerException e) { printError(pOne, false, false, pTwo, false); return; } catch (ImageReadException e) { printError(pOne, false, false, pTwo, false); return; } final long oneLoadTime = System.currentTimeMillis() - time; //getRGB only returns 8 bits per component, so what about 16-bit images? final int[] oneA = imageOne.getRGB(0, 0, imageOne.getWidth(), imageOne.getHeight(), null, 0, imageOne.getWidth()); final int width = imageOne.getWidth(); final int height = imageOne.getHeight(); final boolean greyscale = (imageOne.getType() == BufferedImage.TYPE_BYTE_GRAY || imageOne.getType() == BufferedImage.TYPE_USHORT_GRAY); imageOne = null; time = System.currentTimeMillis(); BufferedImage imageTwo = null; try { imageTwo = Imaging.getBufferedImage(pTwo); } catch (IOException e) { printError(pOne, true, true, pTwo, false); return; } catch (NullPointerException e) { printError(pOne, true, true, pTwo, false); return; } catch (ImageReadException e) { printError(pOne, true, true, pTwo, false); return; } final long twoLoadTime = System.currentTimeMillis() - time; //getRGB only returns 8 bits per component, so what about 16-bit images? final int[] twoA = imageTwo.getRGB(0, 0, imageTwo.getWidth(), imageTwo.getHeight(), null, 0, imageTwo.getWidth()); imageTwo = null; //calculate psnr if wanted time = System.currentTimeMillis(); double psnr = 0; long psnrCalc = 0; if (pCalcPSNR) { psnr = calcPSNR(oneA, twoA, greyscale); psnrCalc = System.currentTimeMillis() - time; } //calculate ssim if wanted time = System.currentTimeMillis(); List<Double> ssimMin = new LinkedList<Double>(); List<Double> ssimVariance = new LinkedList<Double>(); double ssim = 0; long ssimCalc = 0; if (pCalcSSIM) { ssim = calcSSIM(oneA, twoA, width, height, greyscale, pHeatMapImage, ssimMin, ssimVariance); ssimCalc = System.currentTimeMillis() - time; } System.out.println("<dissimilar version=\"" + version + "\">"); System.out.println(" <file loadTimeMS=\"" + oneLoadTime + "\">" + pOne + "</file>"); System.out.println(" <file loadTimeMS=\"" + twoLoadTime + "\">" + pTwo + "</file>"); if (pCalcSSIM) { System.out.println(" <ssim calcTimeMS=\"" + ssimCalc + "\">"); if (ssim > 0) { System.out.println(" <mean>" + new DecimalFormat("0.0000000").format(ssim) + "</mean>"); System.out.println( " <min>" + new DecimalFormat("0.0000000").format(ssimMin.get(0)) + "</min>"); System.out.println(" <variance>" + new DecimalFormat("0.0000000").format(ssimVariance.get(0)) + "</variance>"); } else { System.out.println("failed"); } System.out.println(" </ssim>"); } if (pCalcPSNR) { System.out.println(" <psnr calcTimeMS=\"" + psnrCalc + "\">" + new DecimalFormat("0.0000").format(psnr) + "</psnr>"); } System.out.println("</dissimilar>"); }
From source file:hudson.jbpm.PluginImpl.java
/** * Draws a JPEG for a process definition * //ww w.ja va 2 s. c o m * @param req * @param rsp * @param processDefinition * @throws IOException */ public void doProcessDefinitionImage(StaplerRequest req, StaplerResponse rsp, @QueryParameter("processDefinition") long processDefinition) throws IOException { JbpmContext context = getCurrentJbpmContext(); ProcessDefinition definition = context.getGraphSession().getProcessDefinition(processDefinition); FileDefinition fd = definition.getFileDefinition(); byte[] bytes = fd.getBytes("processimage.jpg"); rsp.setContentType("image/jpeg"); ServletOutputStream output = rsp.getOutputStream(); BufferedImage loaded = ImageIO.read(new ByteArrayInputStream(bytes)); BufferedImage aimg = new BufferedImage(loaded.getWidth(), loaded.getHeight(), BufferedImage.TYPE_INT_RGB); Graphics2D g = aimg.createGraphics(); g.drawImage(loaded, null, 0, 0); g.dispose(); ImageIO.write(aimg, "jpg", output); output.flush(); output.close(); }
From source file:net.rptools.tokentool.AppActions.java
public static void saveToken(File rptok_file, boolean overwrite) { if (rptok_file != null) { if (!rptok_file.getName().toUpperCase().endsWith(".RPTOK")) { rptok_file = new File(rptok_file.getAbsolutePath() + ".rptok"); }// ww w. ja va 2 s . com if (rptok_file.exists() && !overwrite) { if (!TokenTool.confirm("File exists. Overwrite?")) { return; } else { rptok_file.delete(); } } String tokenName = FilenameUtils.removeExtension(rptok_file.getName()); try { // Write out the token image first or aka POG image. File tokenImageFile = File.createTempFile("tokenImage", ".png"); // PW: This code addes the pHYs chunk to the // output png file with X & Y dpi set. BufferedImage tokenImg = TokenTool.getFrame().getComposedToken(); BufferedImage portraitImg = TokenTool.getFrame().getTokenCompositionPanel().getBaseImage(); ImageWriter writer = getImageWriterBySuffix("png"); // Created object for outputStream so we can properly close it! No longer locks .png files until app closes! ImageOutputStream ios = ImageIO.createImageOutputStream(tokenImageFile); writer.setOutput(ios); ImageWriteParam param = writer.getDefaultWriteParam(); PNGMetadata png = new PNGMetadata(); // 39.375 inches per meter // I'm using the image width for the DPI under // the assumption that the token fits within // one cell. int resX = (int) (tokenImg.getWidth() * 39.375f); png.pHYs_pixelsPerUnitXAxis = resX; png.pHYs_pixelsPerUnitYAxis = resX; png.pHYs_unitSpecifier = 1; // Meters - alternative is "unknown" png.pHYs_present = true; writer.write(null, new IIOImage(tokenImg, null, png), param); ios.close(); // Now write out the Portrait image, here we'll use JPEG to save space File portraitImageFile = File.createTempFile("portraitImage", ".jpg"); writer.reset(); writer = getImageWriterBySuffix("jpg"); ios = ImageIO.createImageOutputStream(portraitImageFile); writer.setOutput(ios); param = writer.getDefaultWriteParam(); writer.write(null, new IIOImage(portraitImg, null, null), param); writer.dispose(); ios.close(); // Lets create the token! Token _token = new Token(); Asset tokenImage = null; tokenImage = AssetManager.createAsset(tokenImageFile); AssetManager.putAsset(tokenImage); _token = new Token(tokenName, tokenImage.getId()); _token.setGMName(tokenName); // Jamz: Below calls not needed, creates extra entries in XML preventing token image from changing inside MapTool //_token.setImageAsset(tokenImage.getName()); //_token.setImageAsset(tokenImage.getName(), tokenImage.getId()); // set the image shape Image image = ImageIO.read(tokenImageFile); _token.setShape(TokenUtil.guessTokenType(image)); // set the height/width, fixes dragging to stamp layer issue _token.setHeight(tokenImg.getHeight()); _token.setWidth(tokenImg.getWidth()); // set the portrait image asset Asset portrait = AssetManager.createAsset(portraitImageFile); // Change for portrait AssetManager.putAsset(portrait); _token.setPortraitImage(portrait.getId()); // Time to write out the .rptok token file... PackedFile pakFile = null; try { pakFile = new PackedFile(rptok_file); saveAssets(_token.getAllImageAssets(), pakFile); pakFile.setContent(_token); BufferedImage thumb = ImageUtil.createCompatibleImage(image, THUMB_SIZE, THUMB_SIZE, null); pakFile.putFile(FILE_THUMBNAIL, ImageUtil.imageToBytes(thumb, "png")); pakFile.setProperty(PROP_VERSION, TokenToolFrame.VERSION); pakFile.save(); } catch (Exception e) { e.printStackTrace(); } finally { if (pakFile != null) pakFile.close(); tokenImageFile.delete(); portraitImageFile.delete(); } } catch (IOException ioe) { ioe.printStackTrace(); TokenTool.showError("Unable to write image: " + ioe); } } }
From source file:baocaoxla.xuly_compare.java
public ChartPanel displayhistogram(BufferedImage image) { HistogramDataset dataset = new HistogramDataset(); final int w = image.getWidth(); final int h = image.getHeight(); double[] r = new double[w * h]; double[] g = new double[w * h]; double[] b = new double[w * h]; int dem = 0;/*from w ww . j ava2 s .c om*/ for (int i = 0; i < h; i++) { for (int j = 0; j < w; j++) { Color c = new Color(image.getRGB(j, i)); r[dem] = c.getRed(); g[dem] = c.getGreen(); b[dem] = c.getBlue(); dem++; } } //r = raster.getSamples(0, 0, w, h, 0, r); dataset.addSeries("Red", r, 256); //r = raster.getSamples(0, 0, w, h, 1, r); dataset.addSeries("Green", g, 256); // r = raster.getSamples(0, 0, w, h, 2, r); dataset.addSeries("Blue", b, 256); // chart JFreeChart chart = ChartFactory.createHistogram("Histogram", "Value", "Count", dataset, PlotOrientation.VERTICAL, true, true, false); ChartPanel panel = new ChartPanel(chart); return panel; }