List of usage examples for java.awt RenderingHints KEY_RENDERING
Key KEY_RENDERING
To view the source code for java.awt RenderingHints KEY_RENDERING.
Click Source Link
From source file:org.encuestame.business.images.ImageThumbnailGeneratorImpl.java
/** * Create a thumbnail image and save it to disk. * * This algorithm is based on:/*from www . ja va 2 s .c om*/ * http://www.philreeve.com/java_high_quality_thumbnails.php * * @param imageIn The image you want to scale. * @param fileOut The output file. * @param largestDimension The largest dimension, so that neither the width nor height * will exceed this value. * * @return the image that was created, null if imageIn or fileOut is null. * @throws java.io.IOException if something goes wrong when saving as jpeg */ public BufferedImage createThumbnailImage(Image imageIn, File fileOut, int largestDimension) throws IOException { if ((imageIn == null) || (fileOut == null)) { return null; } //it seems to not return the right size until the methods get called for the first time imageIn.getWidth(null); imageIn.getHeight(null); // Find biggest dimension int nImageWidth = imageIn.getWidth(null); int nImageHeight = imageIn.getHeight(null); int nImageLargestDim = Math.max(nImageWidth, nImageHeight); double scale = (double) largestDimension / (double) nImageLargestDim; int sizeDifference = nImageLargestDim - largestDimension; //create an image buffer to draw to BufferedImage imageOut = new BufferedImage(100, 100, BufferedImage.TYPE_INT_RGB); // 8-bit RGB Graphics2D g2d; AffineTransform tx; // Use a few steps if the sizes are drastically different, and only scale // if the desired size is smaller than the original. int numSteps = 0; if (scale < 1.0d) { // Make sure we have at least 1 step numSteps = Math.max(1, (sizeDifference / 100)); } if (numSteps > 0) { int stepSize = sizeDifference / numSteps; int stepWeight = stepSize / 2; int heavierStepSize = stepSize + stepWeight; int lighterStepSize = stepSize - stepWeight; int currentStepSize, centerStep; double scaledW = imageIn.getWidth(null); double scaledH = imageIn.getHeight(null); if ((numSteps % 2) == 1) //if there's an odd number of steps centerStep = (int) Math.ceil((double) numSteps / 2d); //find the center step else centerStep = -1; //set it to -1 so it's ignored later Integer intermediateSize; Integer previousIntermediateSize = nImageLargestDim; for (Integer i = 0; i < numSteps; i++) { if (i + 1 != centerStep) { //if this isn't the center step if (i == numSteps - 1) { //if this is the last step //fix the stepsize to account for decimal place errors previously currentStepSize = previousIntermediateSize - largestDimension; } else { if (numSteps - i > numSteps / 2) //if we're in the first half of the reductions currentStepSize = heavierStepSize; else currentStepSize = lighterStepSize; } } else { //center step, use natural step size currentStepSize = stepSize; } intermediateSize = previousIntermediateSize - currentStepSize; scale = intermediateSize / (double) previousIntermediateSize; scaledW = Math.max((int) (scaledW * scale), 1); scaledH = Math.max((int) (scaledH * scale), 1); log.info("step " + i + ": scaling to " + scaledW + " x " + scaledH); imageOut = new BufferedImage((int) scaledW, (int) scaledH, BufferedImage.TYPE_INT_RGB); // 8 bit RGB g2d = imageOut.createGraphics(); g2d.setBackground(Color.WHITE); g2d.clearRect(0, 0, imageOut.getWidth(), imageOut.getHeight()); g2d.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY); tx = new AffineTransform(); tx.scale(scale, scale); g2d.drawImage(imageIn, tx, null); g2d.dispose(); imageIn = new ImageIcon(imageOut).getImage(); previousIntermediateSize = intermediateSize; } } else { // This enforces a rule that we always have an 8-bit image with white background for the thumbnail. Plus, for large // images, this makes subsequent downscaling really fast because we are working on a large 8-bit image // instead of a large 12 or 24 bit image, so the downstream effect is very noticable. imageOut = new BufferedImage(imageIn.getWidth(null), imageIn.getHeight(null), BufferedImage.TYPE_INT_RGB); g2d = imageOut.createGraphics(); g2d.setBackground(Color.WHITE); g2d.clearRect(0, 0, imageOut.getWidth(), imageOut.getHeight()); tx = new AffineTransform(); tx.setToIdentity(); //use identity matrix so image is copied exactly g2d.drawImage(imageIn, tx, null); g2d.dispose(); } //saveImageAsJPEG(imageOut, fileOut); ImageIO.write(imageOut, "jpg", fileOut); return imageOut; }
From source file:com.alibaba.simpleimage.ScaleTest.java
public PlanarImage doSubsampleAverage(PlanarImage op) throws Exception { double zoom = dScale; ParameterBlock pb = new ParameterBlock(); pb.addSource(op);//from w w w . j a v a 2 s . co m pb.add(zoom); pb.add(zoom); RenderingHints qualityHints = new RenderingHints(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY); RenderedOp zoomOp = JAI.create("SubsampleAverage", pb, qualityHints); return zoomOp; }
From source file:ddf.catalog.transformer.input.pptx.PptxInputTransformer.java
/** * If the slide show doesn't contain any slides, then return null. Otherwise, return jpeg * image data of the first slide in the deck. * * @param slideShow//from w w w .j a v a 2 s. c om * @return jpeg thumbnail or null if thumbnail can't be created * @throws IOException */ private byte[] generatePptxThumbnail(XMLSlideShow slideShow) throws IOException { if (slideShow.getSlides().isEmpty()) { LOGGER.info("the powerpoint file does not contain any slides, skipping thumbnail generation"); return null; } Dimension pgsize = slideShow.getPageSize(); int largestDimension = (int) Math.max(pgsize.getHeight(), pgsize.getWidth()); float scalingFactor = IMAGE_HEIGHTWIDTH / largestDimension; int scaledHeight = (int) (pgsize.getHeight() * scalingFactor); int scaledWidth = (int) (pgsize.getWidth() * scalingFactor); BufferedImage img = new BufferedImage(scaledWidth, scaledHeight, BufferedImage.TYPE_INT_RGB); Graphics2D graphics = img.createGraphics(); try { graphics.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); graphics.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY); graphics.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BICUBIC); graphics.setRenderingHint(RenderingHints.KEY_FRACTIONALMETRICS, RenderingHints.VALUE_FRACTIONALMETRICS_ON); graphics.scale(scalingFactor, scalingFactor); slideShow.getSlides().get(0).draw(graphics); try (ByteArrayOutputStream outputStream = new ByteArrayOutputStream()) { ImageIOUtil.writeImage(img, FORMAT_NAME, outputStream, RESOLUTION_DPI, IMAGE_QUALITY); return outputStream.toByteArray(); } } catch (RuntimeException e) { if (e.getCause() instanceof javax.imageio.IIOException) { LOGGER.warn("unable to generate thumbnail for PPTX file", e); } else { throw e; } } finally { graphics.dispose(); } return null; }
From source file:org.earthtime.UPb_Redux.dateInterpretation.WeightedMeanGraphPanel.java
/** * * @param g2d//from www . j a va2 s .c o m */ public void paint(Graphics2D g2d) { // setup painting parameters String fractionSortOrder = "name"; //random, weight, date if (getWeightedMeanOptions().containsKey("fractionSortOrder")) { fractionSortOrder = getWeightedMeanOptions().get("fractionSortOrder"); } double rangeX = (getMaxX_Display() - getMinX_Display()); double rangeY = (getMaxY_Display() - getMinY_Display()); g2d.setClip(getLeftMargin(), getTopMargin(), getGraphWidth(), getGraphHeight()); RenderingHints rh = g2d.getRenderingHints(); rh.put(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); rh.put(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY); g2d.setRenderingHints(rh); // walk the sampleDateInterpretations and produce graphs g2d.setPaint(Color.BLACK); g2d.setStroke(new BasicStroke(2.0f)); g2d.setFont(new Font("SansSerif", Font.BOLD, 10)); double barWidth = 15.0; double barGap = 10.0; double startSamX = 10.0; double saveStartSamX = 0.0; double samSpace = 3.0; for (int i = 0; i < selectedSampleDateModels.length; i++) { for (int j = 1; j < 9; j++) { if (selectedSampleDateModels[i][j] instanceof SampleDateModel) { final SampleDateModel SAM = ((SampleDateModel) selectedSampleDateModels[i][j]); double wMean = SAM.getValue().movePointLeft(6).doubleValue(); double wMeanOneSigma = SAM.getOneSigmaAbs().movePointLeft(6).doubleValue(); Path2D mean = new Path2D.Double(Path2D.WIND_NON_ZERO); // july 2008 // modified to show de-selected fractions as gray // this means a new special list of fractionIDs is created fromall non-rejected fractions // and each instance is tested for being included // should eventually refactor Vector<String> allFIDs = new Vector<String>(); for (String f : ((UPbReduxAliquot) SAM.getAliquot()).getAliquotFractionIDs()) { // test added for Sample-based wm if (SAM.fractionDateIsPositive(// ((UPbReduxAliquot) SAM.getAliquot()).getAliquotFractionByName(f))) { allFIDs.add(f); } } final int iFinal = i; if (fractionSortOrder.equalsIgnoreCase("weight")) { Collections.sort(allFIDs, new Comparator<String>() { public int compare(String fID1, String fID2) { double invertOneSigmaF1 = // 1.0 // / ((UPbReduxAliquot) selectedSampleDateModels[iFinal][0])// .getAliquotFractionByName(fID1)// .getRadiogenicIsotopeDateByName(SAM.getDateName())// .getOneSigmaAbs().movePointLeft(6).doubleValue(); double invertOneSigmaF2 = // 1.0 // / ((UPbReduxAliquot) selectedSampleDateModels[iFinal][0])// .getAliquotFractionByName(fID2)// .getRadiogenicIsotopeDateByName(SAM.getDateName())// .getOneSigmaAbs().movePointLeft(6).doubleValue(); return Double.compare(invertOneSigmaF2, invertOneSigmaF1); } }); } else if (fractionSortOrder.equalsIgnoreCase("date")) { Collections.sort(allFIDs, new Comparator<String>() { public int compare(String fID1, String fID2) { double dateF1 = // ((UPbReduxAliquot) selectedSampleDateModels[iFinal][0])// .getAliquotFractionByName(fID1)// .getRadiogenicIsotopeDateByName(SAM.getDateName())// .getValue().doubleValue(); double dateF2 = // ((UPbReduxAliquot) selectedSampleDateModels[iFinal][0])// .getAliquotFractionByName(fID2)// .getRadiogenicIsotopeDateByName(SAM.getDateName())// .getValue().doubleValue(); return Double.compare(dateF1, dateF2); } }); } else if ( /* ! isInRandomMode() &&*/fractionSortOrder.equalsIgnoreCase("random")) { Collections.shuffle(allFIDs, new Random()); } else if (fractionSortOrder.equalsIgnoreCase("name")) { // default to alphabetic by name //Collections.sort(allFIDs); // april 2010 give same lexigraphic ordering that UPbFractions get Collections.sort(allFIDs, new IntuitiveStringComparator<String>()); } else { // do nothing } double actualWidthX = (allFIDs.size()) * (barWidth + barGap);//; + barGap; // plot 2-sigma of mean mean.moveTo((float) mapX(startSamX, getMinX_Display(), rangeX, graphWidth), (float) mapY(wMean + 2.0 * wMeanOneSigma, getMaxY_Display(), rangeY, graphHeight)); mean.lineTo((float) mapX(startSamX + actualWidthX, getMinX_Display(), rangeX, graphWidth), (float) mapY(wMean + 2.0 * wMeanOneSigma, getMaxY_Display(), rangeY, graphHeight)); mean.lineTo((float) mapX(startSamX + actualWidthX, getMinX_Display(), rangeX, graphWidth), (float) mapY(wMean - 2.0 * wMeanOneSigma, getMaxY_Display(), rangeY, graphHeight)); mean.lineTo((float) mapX(startSamX, getMinX_Display(), rangeX, graphWidth), (float) mapY(wMean - 2.0 * wMeanOneSigma, getMaxY_Display(), rangeY, graphHeight)); mean.closePath(); g2d.setColor(ReduxConstants.mySampleYellowColor); g2d.fill(mean); g2d.setPaint(Color.BLACK); // plot 1-sigma of mean mean.reset(); mean.moveTo((float) mapX(startSamX, getMinX_Display(), rangeX, graphWidth), (float) mapY(wMean + wMeanOneSigma, getMaxY_Display(), rangeY, graphHeight)); mean.lineTo((float) mapX(startSamX + actualWidthX, getMinX_Display(), rangeX, graphWidth), (float) mapY(wMean + wMeanOneSigma, getMaxY_Display(), rangeY, graphHeight)); mean.lineTo((float) mapX(startSamX + actualWidthX, getMinX_Display(), rangeX, graphWidth), (float) mapY(wMean - wMeanOneSigma, getMaxY_Display(), rangeY, graphHeight)); mean.lineTo((float) mapX(startSamX, getMinX_Display(), rangeX, graphWidth), (float) mapY(wMean - wMeanOneSigma, getMaxY_Display(), rangeY, graphHeight)); mean.closePath(); g2d.setColor(ReduxConstants.ColorOfRedux); g2d.fill(mean); g2d.setPaint(Color.BLACK); // plot mean mean.reset(); mean.moveTo((float) mapX(startSamX, getMinX_Display(), rangeX, graphWidth), (float) mapY(wMean, getMaxY_Display(), rangeY, graphHeight)); mean.lineTo((float) mapX(startSamX + actualWidthX, getMinX_Display(), rangeX, graphWidth), (float) mapY(wMean, getMaxY_Display(), rangeY, graphHeight)); g2d.setStroke(new BasicStroke(1.0f)); g2d.draw(mean); g2d.setStroke(new BasicStroke(2.0f)); saveStartSamX = startSamX; // plot fraction bars double minPoint = 5000.0; double maxWeight = 0.0; double totalWeight = 0.0; int barNum = 0; for (String fID : allFIDs) { // the dateModel has an associated aliquot, but in sample mode, it is a // standin aliquot for the sample. to get the aliquot number for // use in coloring fractions, we need to query the fraction itself String aliquotName = sample.getAliquotNameByFractionID(fID); Color includedFillColor = new Color(0, 0, 0); if (sample.getSampleDateInterpretationGUISettings().getAliquotOptions().get(aliquotName) .containsKey("includedFillColor")) { String[] temp = // sample.getSampleDateInterpretationGUISettings().getAliquotOptions() .get(aliquotName).get("includedFillColor").split(","); includedFillColor = buildRGBColor(temp); } Fraction f = ((UPbReduxAliquot) selectedSampleDateModels[i][0]) .getAliquotFractionByName(fID); double date = f.//((UPbReduxAliquot) selectedSampleDateModels[i][0]).getAliquotFractionByName(fID).// getRadiogenicIsotopeDateByName(SAM.getDateName()).getValue().movePointLeft(6) .doubleValue(); double twoSigma = f.//((UPbReduxAliquot) selectedSampleDateModels[i][0]).getAliquotFractionByName(fID).// getRadiogenicIsotopeDateByName(SAM.getDateName()).getTwoSigmaAbs().movePointLeft(6) .doubleValue(); if ((date - twoSigma) < minPoint) { minPoint = (date - twoSigma); } double invertedOneSigma = // 1.0 // / f.//((UPbReduxAliquot) selectedSampleDateModels[i][0]).getAliquotFractionByName(fID).// getRadiogenicIsotopeDateByName(SAM.getDateName()).getOneSigmaAbs() .movePointLeft(6).doubleValue(); if (invertedOneSigma > maxWeight) { maxWeight = invertedOneSigma; } Path2D bar = new Path2D.Double(Path2D.WIND_NON_ZERO); bar.moveTo( (float) mapX(saveStartSamX + ((barGap / 2.0) + barNum * (barWidth + barGap)), getMinX_Display(), rangeX, graphWidth), (float) mapY(date + twoSigma, getMaxY_Display(), rangeY, graphHeight)); bar.lineTo( (float) mapX( saveStartSamX + ((barGap / 2.0) + barNum * (barWidth + barGap)) + barWidth, getMinX_Display(), rangeX, graphWidth), (float) mapY(date + twoSigma, getMaxY_Display(), rangeY, graphHeight)); bar.lineTo( (float) mapX( saveStartSamX + ((barGap / 2.0) + barNum * (barWidth + barGap)) + barWidth, getMinX_Display(), rangeX, graphWidth), (float) mapY(date - twoSigma, getMaxY_Display(), rangeY, graphHeight)); bar.lineTo( (float) mapX(saveStartSamX + ((barGap / 2.0) + barNum * (barWidth + barGap)), getMinX_Display(), rangeX, graphWidth), (float) mapY(date - twoSigma, getMaxY_Display(), rangeY, graphHeight)); bar.closePath(); Composite originalComposite = g2d.getComposite(); if (SAM.getIncludedFractionIDsVector().contains(fID)) { g2d.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 0.8f)); totalWeight += Math.pow(invertedOneSigma, 2.0); // april 2014 experiment if (f.getRgbColor() != 0) { includedFillColor = new Color(f.getRgbColor()); } } else { g2d.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 0.2f)); } g2d.setPaint(includedFillColor); g2d.draw(bar); //restore composite g2d.setComposite(originalComposite); g2d.setColor(Color.black); // label fraction at top g2d.rotate(-Math.PI / 4.0, (float) mapX(saveStartSamX + ((barGap / 2.0) + barNum * (barWidth + barGap)), getMinX_Display(), rangeX, graphWidth), (float) mapY(date + twoSigma, getMaxY_Display(), rangeY, graphHeight)); g2d.drawString( ((UPbReduxAliquot) selectedSampleDateModels[i][0]).getAliquotFractionByName(fID) .getFractionID(), (float) mapX(saveStartSamX + ((barGap / 2.0) + barNum * (barWidth + barGap)), getMinX_Display(), rangeX, graphWidth) + 15, (float) mapY(date + twoSigma, getMaxY_Display(), rangeY, graphHeight)); g2d.rotate(Math.PI / 4.0, (float) mapX(saveStartSamX + ((barGap / 2.0) + barNum * (barWidth + barGap)), getMinX_Display(), rangeX, graphWidth), (float) mapY(date + twoSigma, getMaxY_Display(), rangeY, graphHeight)); barNum++; // startSamX += 2 * barWidth; startSamX += barWidth + barGap; } // display three info boxes below weighted means // each tic is the height of one calculated y-axis tic // determine the y axis tic double minYtic = Math.ceil(getMinY_Display() * 100) / 100; double maxYtic = Math.floor(getMaxY_Display() * 100) / 100; double deltay = Math.rint((maxYtic - minYtic) * 10 + 0.5); double yTic = deltay / 100; double yTopSummary = minPoint - yTic / 2.0;// wMeanOneSigma; //double specialYTic = yTic; double yTopWeights = yTopSummary - yTic * 1.1; double yTopMSWD_PDF = yTopWeights - yTic * 1.1; // summary box Path2D box = new Path2D.Double(Path2D.WIND_NON_ZERO); box.moveTo((float) mapX(saveStartSamX, getMinX_Display(), rangeX, graphWidth), (float) mapY(yTopSummary, getMaxY_Display(), rangeY, graphHeight)); box.lineTo((float) mapX(saveStartSamX + actualWidthX, getMinX_Display(), rangeX, graphWidth), (float) mapY(yTopSummary, getMaxY_Display(), rangeY, graphHeight)); box.lineTo((float) mapX(saveStartSamX + actualWidthX, getMinX_Display(), rangeX, graphWidth), (float) mapY(yTopSummary - yTic, getMaxY_Display(), rangeY, graphHeight)); box.lineTo((float) mapX(saveStartSamX, getMinX_Display(), rangeX, graphWidth), (float) mapY(yTopSummary - yTic, getMaxY_Display(), rangeY, graphHeight)); box.closePath(); g2d.setStroke(new BasicStroke(1.5f)); g2d.draw(box); // Info Box g2d.drawString(// SAM.getAliquot().getAliquotName(), (float) mapX(saveStartSamX, getMinX_Display(), rangeX, graphWidth) + 4f, (float) mapY(yTopSummary, getMaxY_Display(), rangeY, graphHeight) + 13f); g2d.drawString(// SAM.getName(), (float) mapX(saveStartSamX, getMinX_Display(), rangeX, graphWidth) + 4f, (float) mapY(yTopSummary, getMaxY_Display(), rangeY, graphHeight) + 25f); g2d.drawString(// SAM.FormatValueAndTwoSigmaABSThreeWaysForPublication(6, 2), (float) mapX(saveStartSamX, getMinX_Display(), rangeX, graphWidth) + 4f, (float) mapY(yTopSummary, getMaxY_Display(), rangeY, graphHeight) + 36f); g2d.drawString(// SAM.ShowCustomMSWDwithN(), (float) mapX(saveStartSamX, getMinX_Display(), rangeX, graphWidth) + 4f, (float) mapY(yTopSummary, getMaxY_Display(), rangeY, graphHeight) + 48f); // weights box box.reset(); box.moveTo((float) mapX(saveStartSamX, getMinX_Display(), rangeX, graphWidth), (float) mapY(yTopWeights, getMaxY_Display(), rangeY, graphHeight)); box.lineTo((float) mapX(saveStartSamX + actualWidthX, getMinX_Display(), rangeX, graphWidth), (float) mapY(yTopWeights, getMaxY_Display(), rangeY, graphHeight)); box.lineTo((float) mapX(saveStartSamX + actualWidthX, getMinX_Display(), rangeX, graphWidth), (float) mapY(yTopWeights - yTic, getMaxY_Display(), rangeY, graphHeight)); box.lineTo((float) mapX(saveStartSamX, getMinX_Display(), rangeX, graphWidth), (float) mapY(yTopWeights - yTic, getMaxY_Display(), rangeY, graphHeight)); box.closePath(); g2d.setStroke(new BasicStroke(1.5f)); g2d.draw(box); // plot fraction weights double artificialXRange = allFIDs.size(); double count = 0; //double weightWidth = Math.min(3.0 * barWidth, (yTic / rangeY * graphHeight)) - 15;//yTic;//barWidth * 2.0; double weightWidth = (barWidth + barGap) * 0.9; for (String fID : allFIDs) { // the dateModel has an associated aliquot, but in sample mode, it is a // standin aliquot for the sample. to get the aliquot number for // use in coloring fractions, we need to query the fraction itself String aliquotName = sample.getAliquotNameByFractionID(fID); Fraction f = ((UPbReduxAliquot) selectedSampleDateModels[i][0]) .getAliquotFractionByName(fID); Color includedFillColor = new Color(0, 0, 0); if (sample.getSampleDateInterpretationGUISettings().getAliquotOptions().get(aliquotName) .containsKey("includedFillColor")) { String[] temp = // sample.getSampleDateInterpretationGUISettings().getAliquotOptions() .get(aliquotName).get("includedFillColor").split(","); includedFillColor = buildRGBColor(temp); } double invertOneSigma = // 1.0 // / ((UPbReduxAliquot) selectedSampleDateModels[i][0]) .getAliquotFractionByName(fID)// .getRadiogenicIsotopeDateByName(SAM.getDateName()).getOneSigmaAbs() .movePointLeft(6).doubleValue(); Path2D weight = new Path2D.Double(Path2D.WIND_NON_ZERO); weight.moveTo( (float) mapX(saveStartSamX + (count + 0.5) / artificialXRange * actualWidthX, getMinX_Display(), rangeX, graphWidth) // - (float) (invertOneSigma / maxWeight / 2.0 * weightWidth), (float) mapY(yTopWeights - (yTic / 2.0), getMaxY_Display(), rangeY, graphHeight) // + (float) (invertOneSigma / maxWeight / 2.0 * weightWidth) - 5f); weight.lineTo( (float) mapX(saveStartSamX + (count + 0.5) / artificialXRange * actualWidthX, getMinX_Display(), rangeX, graphWidth) // + (float) (invertOneSigma / maxWeight / 2.0 * weightWidth), (float) mapY(yTopWeights - (yTic / 2.0), getMaxY_Display(), rangeY, graphHeight) // + (float) (invertOneSigma / maxWeight / 2.0 * weightWidth) - 5f); weight.lineTo( (float) mapX(saveStartSamX + (count + 0.5) / artificialXRange * actualWidthX, getMinX_Display(), rangeX, graphWidth) // + (float) (invertOneSigma / maxWeight / 2.0 * weightWidth), (float) mapY(yTopWeights - (yTic / 2.0), getMaxY_Display(), rangeY, graphHeight) // - (float) (invertOneSigma / maxWeight / 2.0 * weightWidth) - 5f); weight.lineTo( (float) mapX(saveStartSamX + (count + 0.5) / artificialXRange * actualWidthX, getMinX_Display(), rangeX, graphWidth) // - (float) (invertOneSigma / maxWeight / 2.0 * weightWidth), (float) mapY(yTopWeights - (yTic / 2.0), getMaxY_Display(), rangeY, graphHeight) // - (float) (invertOneSigma / maxWeight / 2.0 * weightWidth) - 5f); weight.closePath(); g2d.setStroke(new BasicStroke(2.5f)); // test for included or not == black or gray String weightPerCent = " 0";//0.0%"; // g2d.setPaint(includedFillColor); Composite originalComposite = g2d.getComposite(); if (SAM.getIncludedFractionIDsVector().contains(fID)) { g2d.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 0.8f)); weightPerCent = formatter1DecPlace .format(Math.pow(invertOneSigma, 2.0) / totalWeight * 100.0);// + "%"; // april 2014 experiment if (f.getRgbColor() != 0) { includedFillColor = new Color(f.getRgbColor()); } } else { g2d.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 0.2f)); } g2d.setPaint(includedFillColor); g2d.fill(weight); //restore composite g2d.setComposite(originalComposite); // write percent of total weight g2d.drawString(weightPerCent, (float) mapX(saveStartSamX + (count + 0.5) / artificialXRange * actualWidthX, getMinX_Display(), rangeX, graphWidth) // - (float) (invertOneSigma / maxWeight / 2.0 * weightWidth), (float) mapY(yTopWeights - yTic, getMaxY_Display(), rangeY, graphHeight) - 5f); g2d.setColor(Color.black); count += 1.0; } // double box height for graph yTic *= 2.0; // plot MSWD_PDF // store function x,y values Vector<Double> xVals = new Vector<Double>(); Vector<Double> yVals = new Vector<Double>(); double f = SAM.getIncludedFractionIDsVector().size() - 1; if (f > 1.0) { g2d.setStroke(new BasicStroke(1.0f)); double yRange = MSWDCoordinates.valuesByPointCount[(int) f][5] * 1.03; // alitle air at the top of curve double xStart = MSWDCoordinates.valuesByPointCount[(int) f][1]; double xRange = MSWDCoordinates.valuesByPointCount[(int) f][4] - xStart; double xStep = 0.005; Path2D MSWD_PDF = new Path2D.Double(Path2D.WIND_NON_ZERO); Path2D MSWD_right = new Path2D.Double(Path2D.WIND_NON_ZERO); // start at lower left corner of box (may or may not be 0,0 ) MSWD_PDF.moveTo(// (float) mapX((double) saveStartSamX, getMinX_Display(), rangeX, graphWidth), (float) mapY(yTopMSWD_PDF - yTic, getMaxY_Display(), rangeY, graphHeight)); // setup MSWD to paint last Path2D MSWD = null; // calculate function values for (double x = xStart; x < xRange; x += xStep) { xVals.add((((x - xStart) / xRange) * actualWidthX) + (double) saveStartSamX); double y = // Math.pow(2, -1.0 * f / 2.0)// * Math.exp(-1.0 * f * x / 2.0)// * Math.pow(f, f / 2.0)// * Math.pow(x, (-1.0 + f / 2.0))// / Math.exp(Gamma.logGamma(f / 2.0)); yVals.add(((y / yRange) * yTic) + yTopMSWD_PDF - yTic); MSWD_PDF.lineTo(// (float) mapX(xVals.lastElement(), getMinX_Display(), rangeX, graphWidth), (float) mapY(yVals.lastElement(), getMaxY_Display(), rangeY, graphHeight)); // test for location of left RED zone if ((MSWDCoordinates.valuesByPointCount[(int) f][2] >= x) && (MSWDCoordinates.valuesByPointCount[(int) f][2] < (x + xStep))) { double leftX = MSWDCoordinates.valuesByPointCount[(int) f][2]; xVals.add((((leftX - xStart) / xRange) * actualWidthX) + (double) saveStartSamX); double leftY = // Math.pow(2, -1.0 * f / 2.0)// * Math.exp(-1.0 * f * leftX / 2.0)// * Math.pow(f, f / 2.0)// * Math.pow(leftX, (-1.0 + f / 2.0))// / Math.exp(Gamma.logGamma(f / 2.0)); yVals.add(((leftY / yRange) * yTic) + yTopMSWD_PDF - yTic); MSWD_PDF.lineTo(// (float) mapX(xVals.lastElement(), getMinX_Display(), rangeX, graphWidth), (float) mapY(yVals.lastElement(), getMaxY_Display(), rangeY, graphHeight)); Path2D ciLower = new Path2D.Double(Path2D.WIND_NON_ZERO); ciLower.append(MSWD_PDF.getPathIterator(new AffineTransform()), true); ciLower.lineTo(// (float) mapX(xVals.lastElement(), getMinX_Display(), rangeX, graphWidth), (float) mapY(yTopMSWD_PDF - yTic, getMaxY_Display(), rangeY, graphHeight)); ciLower.closePath(); g2d.setColor(Color.RED); g2d.fill(ciLower); // draw right hand border line to compensate for a bug in the filler Line2D right = new Line2D.Double(// mapX(xVals.lastElement(), getMinX_Display(), rangeX, graphWidth), mapY(yVals.lastElement(), getMaxY_Display(), rangeY, graphHeight), mapX(xVals.lastElement(), getMinX_Display(), rangeX, graphWidth), mapY(yTopMSWD_PDF - yTic, getMaxY_Display(), rangeY, graphHeight)); g2d.setStroke(new BasicStroke(0.5f)); g2d.draw(right); g2d.setStroke(new BasicStroke(1.0f)); g2d.setColor(Color.BLACK); System.out.println("Left Red = (" + leftX + ", " + leftY + ")"); } // test for location of right RED zone if ((MSWDCoordinates.valuesByPointCount[(int) f][3] >= x) && (MSWDCoordinates.valuesByPointCount[(int) f][3] < (x + xStep))) { double rightX = MSWDCoordinates.valuesByPointCount[(int) f][3]; xVals.add((((rightX - xStart) / xRange) * actualWidthX) + (double) saveStartSamX); double rightY = // Math.pow(2, -1.0 * f / 2.0)// * Math.exp(-1.0 * f * rightX / 2.0)// * Math.pow(f, f / 2.0)// * Math.pow(rightX, (-1.0 + f / 2.0))// / Math.exp(Gamma.logGamma(f / 2.0)); yVals.add(((rightY / yRange) * yTic) + yTopMSWD_PDF - yTic); MSWD_PDF.lineTo(// (float) mapX(xVals.lastElement(), getMinX_Display(), rangeX, graphWidth), (float) mapY(yVals.lastElement(), getMaxY_Display(), rangeY, graphHeight)); // here the strategy is to draw the curve and then reset it to record the remainder g2d.setStroke(new BasicStroke(1.0f)); g2d.draw(MSWD_PDF); MSWD_PDF = new Path2D.Double(Path2D.WIND_NON_ZERO); MSWD_PDF.moveTo(// (float) mapX(xVals.lastElement(), getMinX_Display(), rangeX, graphWidth), (float) mapY(yVals.lastElement(), getMaxY_Display(), rangeY, graphHeight)); MSWD_right.moveTo(// (float) mapX(xVals.lastElement(), getMinX_Display(), rangeX, graphWidth), (float) mapY(yTopMSWD_PDF - yTic, getMaxY_Display(), rangeY, graphHeight)); MSWD_right.lineTo(// (float) mapX(xVals.lastElement(), getMinX_Display(), rangeX, graphWidth), (float) mapY(yVals.lastElement(), getMaxY_Display(), rangeY, graphHeight)); System.out.println("Right Red = (" + rightX + ", " + rightY + ")"); } // test for location of MSWD AND paint last if ((SAM.getMeanSquaredWeightedDeviation().doubleValue() >= x) && (SAM.getMeanSquaredWeightedDeviation().doubleValue() < (x + xStep))) { MSWD = new Path2D.Double(Path2D.WIND_NON_ZERO); MSWD.moveTo(// (float) mapX(xVals.lastElement(), getMinX_Display(), rangeX, graphWidth), (float) mapY(yTopMSWD_PDF - yTic, getMaxY_Display(), rangeY, graphHeight)); MSWD.lineTo(// (float) mapX(xVals.lastElement(), getMinX_Display(), rangeX, graphWidth), (float) mapY(yVals.lastElement(), getMaxY_Display(), rangeY, graphHeight)); } } g2d.setStroke(new BasicStroke(1.0f)); // merge with border of right RED and fill MSWD_right.append(MSWD_PDF.getPathIterator(new AffineTransform()), true); g2d.setColor(Color.RED); g2d.fill(MSWD_right); g2d.setColor(Color.BLACK); // draw the remaining curves g2d.draw(MSWD_PDF); // MSWD may be off the graph and hence not exist try { g2d.draw(MSWD); } catch (Exception e) { } // label 95% conf interval and MSWD g2d.drawString(// "95% CI: (" + formatter2DecPlaces.format(MSWDCoordinates.valuesByPointCount[(int) f][2]) + ", " + formatter2DecPlaces.format(MSWDCoordinates.valuesByPointCount[(int) f][3]) + ")", (float) mapX(saveStartSamX + (actualWidthX / 2.0), getMinX_Display(), rangeX, graphWidth) - 30f, (float) mapY(yTopMSWD_PDF, getMaxY_Display(), rangeY, graphHeight) + 15f); // determine if MSWD is out of range String mswdAlert = ""; if (SAM.getMeanSquaredWeightedDeviation() .doubleValue() > MSWDCoordinates.valuesByPointCount[(int) f][4]) { mswdAlert = "\n !Out of Range!"; } g2d.drawString(// "MSWD = " + formatter2DecPlaces .format(SAM.getMeanSquaredWeightedDeviation().doubleValue()) + ", n = " + (int) (f + 1) + mswdAlert, (float) mapX(saveStartSamX + (actualWidthX / 2.0), getMinX_Display(), rangeX, graphWidth) - 15f, (float) mapY(yTopMSWD_PDF, getMaxY_Display(), rangeY, graphHeight) + 30f); } else { g2d.drawString("need more data...", (float) mapX((double) saveStartSamX, getMinX_Display(), rangeX, graphWidth) + 4f, (float) mapY(yTopMSWD_PDF - yTic, getMaxY_Display(), rangeY, graphHeight) - 10f); } // MSWD_PDF box box.reset(); box.moveTo((float) mapX(saveStartSamX, getMinX_Display(), rangeX, graphWidth), (float) mapY(yTopMSWD_PDF, getMaxY_Display(), rangeY, graphHeight)); box.lineTo((float) mapX(saveStartSamX + actualWidthX, getMinX_Display(), rangeX, graphWidth), (float) mapY(yTopMSWD_PDF, getMaxY_Display(), rangeY, graphHeight)); box.lineTo((float) mapX(saveStartSamX + actualWidthX, getMinX_Display(), rangeX, graphWidth), (float) mapY(yTopMSWD_PDF - yTic, getMaxY_Display(), rangeY, graphHeight)); box.lineTo((float) mapX(saveStartSamX, getMinX_Display(), rangeX, graphWidth), (float) mapY(yTopMSWD_PDF - yTic, getMaxY_Display(), rangeY, graphHeight)); box.closePath(); g2d.setStroke(new BasicStroke(1.5f)); g2d.draw(box); // MSWD_PDF x-axis tics if (f > 1.0) { g2d.setStroke(new BasicStroke(1.0f)); double xStart = (MSWDCoordinates.valuesByPointCount[(int) f][1] <= 0.5) ? 0.5 : 1.0; double xRange = MSWDCoordinates.valuesByPointCount[(int) f][4] - MSWDCoordinates.valuesByPointCount[(int) f][1]; double xStep = 0.5; for (double x = xStart; x < xRange; x += xStep) { double xPlot = (((x - MSWDCoordinates.valuesByPointCount[(int) f][1]) / xRange) * actualWidthX) + (double) saveStartSamX; Line2D line = new Line2D.Double(mapX(xPlot, getMinX_Display(), rangeX, graphWidth), mapY(yTopMSWD_PDF - yTic, getMaxY_Display(), rangeY, graphHeight), mapX(xPlot, getMinX_Display(), rangeX, graphWidth), mapY(yTopMSWD_PDF - yTic, getMaxY_Display(), rangeY, graphHeight) + 7); g2d.draw(line); g2d.rotate(-Math.PI / 2.0, (float) mapX(xPlot, getMinX_Display(), rangeX, graphWidth), (float) mapY(yTopMSWD_PDF - yTic, getMaxY_Display(), rangeY, graphHeight)); g2d.drawString(formatter1DecPlace.format(x), (float) mapX(xPlot, getMinX_Display(), rangeX, graphWidth) - 30f, (float) mapY(yTopMSWD_PDF - yTic, getMaxY_Display(), rangeY, graphHeight) + 5f); g2d.rotate(Math.PI / 2.0, (float) mapX(xPlot, getMinX_Display(), rangeX, graphWidth), (float) mapY(yTopMSWD_PDF - yTic, getMaxY_Display(), rangeY, graphHeight)); } } // set counters barNum += samSpace; startSamX += 2 * samSpace * barWidth; } } } // // prevents re-randomization // setInRandomMode( true ); drawAxesAndTicks(g2d, rangeX, rangeY); // draw zoom box if in use if ((Math.abs(zoomMaxX - zoomMinX) * Math.abs(zoomMinY - zoomMaxY)) > 0.0) { g2d.setStroke(new BasicStroke(2.0f)); g2d.setColor(Color.red); g2d.drawRect(// Math.min(zoomMinX, zoomMaxX), Math.min(zoomMaxY, zoomMinY), Math.abs(zoomMaxX - zoomMinX), Math.abs(zoomMinY - zoomMaxY)); } }
From source file:org.elasticwarehouse.core.parsers.FileTools.java
private static BufferedImage resizeImageWithHint(BufferedImage originalImage, int type, int IMG_WIDTH, int IMG_HEIGHT) { BufferedImage resizedImage = new BufferedImage(IMG_WIDTH, IMG_HEIGHT, type); Graphics2D g = resizedImage.createGraphics(); g.drawImage(originalImage, 0, 0, IMG_WIDTH, IMG_HEIGHT, null); g.dispose();/*from ww w .j ava 2 s . c o m*/ g.setComposite(AlphaComposite.Src); g.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR); g.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY); g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); return resizedImage; }
From source file:org.polymap.service.geoserver.spring.PipelineMapProducer.java
public void writeTo(final OutputStream out) throws ServiceException, IOException { Timer timer = new Timer(); // single layer? -> request ENCODED_IMAGE if (mapContext.getLayerCount() == 1) { MapLayer mapLayer = mapContext.getLayers()[0]; ILayer layer = loader.findLayer(mapLayer); try {/*from w w w.j ava2 s .c o m*/ Pipeline pipeline = loader.getOrCreatePipeline(layer, LayerUseCase.ENCODED_IMAGE); ProcessorRequest request = prepareProcessorRequest(); pipeline.process(request, new ResponseHandler() { public void handle(ProcessorResponse pipeResponse) throws Exception { HttpServletResponse response = GeoServerWms.response.get(); if (pipeResponse == EncodedImageResponse.NOT_MODIFIED) { log.info("Response: 304!"); response.setStatus(304); } else { long lastModified = ((EncodedImageResponse) pipeResponse).getLastModified(); // allow caches and browser clients to cache for 1h //response.setHeader( "Cache-Control", "public,max-age=3600" ); if (lastModified > 0) { response.setHeader("Cache-Control", "no-cache,must-revalidate"); response.setDateHeader("Last-Modified", lastModified); } else { response.setHeader("Cache-Control", "no-cache,must-revalidate"); response.setDateHeader("Expires", 0); } byte[] chunk = ((EncodedImageResponse) pipeResponse).getChunk(); int len = ((EncodedImageResponse) pipeResponse).getChunkSize(); out.write(chunk, 0, len); } } }); log.debug(" flushing response stream. (" + timer.elapsedTime() + "ms)"); out.flush(); } catch (IOException e) { throw e; } catch (Exception e) { throw new IOException(e); } } // multiple layers -> render into one image else { List<Job> jobs = new ArrayList(); final Map<MapLayer, Image> images = new HashMap(); // run jobs for all layers for (final MapLayer mapLayer : mapContext.getLayers()) { final ILayer layer = loader.findLayer(mapLayer); // job UIJob job = new UIJob(getClass().getSimpleName() + ": " + layer.getLabel()) { protected void runWithException(IProgressMonitor monitor) throws Exception { try { // XXX this excludes Cache304 (which support EncodedImageResponse only) Pipeline pipeline = loader.getOrCreatePipeline(layer, LayerUseCase.IMAGE); GetMapRequest targetRequest = prepareProcessorRequest(); pipeline.process(targetRequest, new ResponseHandler() { public void handle(ProcessorResponse pipeResponse) throws Exception { Image layerImage = ((ImageResponse) pipeResponse).getImage(); images.put(mapLayer, layerImage); } }); } catch (Exception e) { // XXX put a special image in the map log.warn("", e); images.put(mapLayer, null); throw e; } } }; job.schedule(); jobs.add(job); } // join jobs for (Job job : jobs) { try { job.join(); } catch (InterruptedException e) { // XXX put a special image in the map log.warn("", e); } } // put images together (MapContext order) Graphics2D g = null; try { // result image BufferedImage result = ImageUtils.createImage(mapContext.getMapWidth(), mapContext.getMapHeight(), null, true); g = result.createGraphics(); // rendering hints RenderingHints hints = new RenderingHints(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY); hints.add(new RenderingHints(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON)); hints.add(new RenderingHints(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON)); g.setRenderingHints(hints); for (MapLayer mapLayer : mapContext.getLayers()) { Image layerImage = images.get(mapLayer); // load image data // new javax.swing.ImageIcon( image ).getImage(); ILayer layer = loader.findLayer(mapLayer); int rule = AlphaComposite.SRC_OVER; float alpha = ((float) layer.getOpacity()) / 100; g.setComposite(AlphaComposite.getInstance(rule, alpha)); g.drawImage(layerImage, 0, 0, null); } encodeImage(result, out); } finally { if (g != null) { g.dispose(); } } } }
From source file:dcstore.web.ImagesWeb.java
private void resizeImage(String inPath, int w, int h, String outPath) { try {// w ww. j a va 2 s. co m BufferedImage originalImage = ImageIO.read(new File(inPath)); int ow, oh; ow = originalImage.getWidth(); oh = originalImage.getHeight(); double ratio = (double) ow / (double) oh; int type = originalImage.getType() == 0 ? BufferedImage.TYPE_INT_ARGB : originalImage.getType(); int ch = (int) Math.round(w / ratio); BufferedImage resizedImage = new BufferedImage(w, h, type); Graphics2D g = resizedImage.createGraphics(); g.setComposite(AlphaComposite.Src); g.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR); g.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY); g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); g.setColor(Color.white); g.fillRect(0, 0, w, h); g.drawImage(originalImage, 0, (int) (((float) h - (float) ch) / 2), w, ch, null); g.dispose(); ImageIO.write(resizedImage, "jpg", new File(outPath)); } catch (Exception e) { FacesContext.getCurrentInstance().addMessage("", new FacesMessage("Error while resizeing image: " + e.getMessage())); } }
From source file:org.polymap.core.data.image.RasterRenderProcessor.java
protected Image getMap(Set<ILayer> layers, int width, int height, ReferencedEnvelope bbox) { // mapContext synchronized (this) { // check style objects boolean needsNewContext = false; // create mapContext if (mapContext == null || needsNewContext) { // sort z-priority TreeMap<String, ILayer> sortedLayers = new TreeMap(); for (ILayer layer : layers) { String uniqueOrderKey = String.valueOf(layer.getOrderKey()) + layer.id(); sortedLayers.put(uniqueOrderKey, layer); }//ww w. ja v a2 s .co m // add to mapContext mapContext = new DefaultMapContext(bbox.getCoordinateReferenceSystem()); for (ILayer layer : sortedLayers.values()) { try { IGeoResource res = layer.getGeoResource(); if (res == null) { throw new IllegalStateException("Unable to find geo resource of layer: " + layer); } AbstractRasterService service = (AbstractRasterService) res.service(null); log.debug(" service: " + service); log.debug(" CRS: " + layer.getCRS()); AbstractGridCoverage2DReader reader = service.getReader(layer.getCRS(), null); Style style = createRGBStyle(reader); if (style == null) { log.warn("Error creating RGB style, trying greyscale..."); style = createGreyscaleStyle(1); } mapContext.addLayer(reader, style); styles.put(layer, style); } catch (IOException e) { log.warn(e); // FIXME set layer status and statusMessage } } } else { } } // render BufferedImage result = new BufferedImage(width, height, BufferedImage.TYPE_4BYTE_ABGR); final Graphics2D g = result.createGraphics(); try { StreamingRenderer renderer = new StreamingRenderer(); // error handler renderer.addRenderListener(new RenderListener() { public void featureRenderer(SimpleFeature feature) { } public void errorOccurred(Exception e) { log.error("Renderer error: ", e); drawErrorMsg(g, "Fehler bei der Darstellung.", e); } }); // rendering hints RenderingHints hints = new RenderingHints(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY); hints.add(new RenderingHints(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON)); hints.add(new RenderingHints(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON)); renderer.setJava2DHints(hints); // g.setRenderingHints( hints ); // render params Map rendererParams = new HashMap(); rendererParams.put("optimizedDataLoadingEnabled", Boolean.TRUE); renderer.setRendererHints(rendererParams); renderer.setContext(mapContext); Rectangle paintArea = new Rectangle(width, height); renderer.paint(g, paintArea, bbox); return result; } catch (Throwable e) { log.error("Renderer error: ", e); drawErrorMsg(g, null, e); return result; } finally { if (g != null) { g.dispose(); } } }
From source file:oulib.aws.s3.S3Util.java
/** * Generate a small tiff file from large Tiff S3 bucket object <br> * Note: the small tiff file will have the same key path as the original one * //from w ww . j a va2 s.c o m * @param s3client : S3 client * @param s3 : S3 object that con * @param targetBucketName : the bucket that stores the small tiff file * @param targetKey : key of the object in the target bucket * @param compressionRate : compression rate * @return : PutObjectResult */ public static PutObjectResult generateSmallTiff(AmazonS3 s3client, S3Object s3, String targetBucketName, String targetKey, double compressionRate) { PutObjectResult result = null; ByteArrayOutputStream bos = null; ByteArrayOutputStream os = null; ByteArrayInputStream is = null; S3ObjectInputStream s = null; ByteArrayInputStream byteInputStream = null; try { System.setProperty("com.sun.media.jai.disableMediaLib", "true"); bos = new ByteArrayOutputStream(); s = s3.getObjectContent(); byte[] bytes = IOUtils.toByteArray(s); byteInputStream = new ByteArrayInputStream(bytes); TIFFDecodeParam param = new TIFFDecodeParam(); ImageDecoder dec = ImageCodec.createImageDecoder("TIFF", byteInputStream, param); RenderedImage image = dec.decodeAsRenderedImage(); RenderingHints qualityHints = new RenderingHints(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY); RenderedOp resizedImage = JAI.create("SubsampleAverage", image, compressionRate, compressionRate, qualityHints); TIFFEncodeParam params = new com.sun.media.jai.codec.TIFFEncodeParam(); resizedImage = JAI.create("encode", resizedImage, bos, "TIFF", params); BufferedImage imagenew = resizedImage.getSourceImage(0).getAsBufferedImage(); os = new ByteArrayOutputStream(); ImageIO.write(imagenew, "tif", os); is = new ByteArrayInputStream(os.toByteArray()); ObjectMetadata metadata = new ObjectMetadata(); metadata.setContentLength(os.toByteArray().length); metadata.setContentType("image/tiff"); metadata.setLastModified(new Date()); os.close(); imagenew.flush(); result = s3client.putObject(new PutObjectRequest(targetBucketName, targetKey, is, metadata)); } catch (IOException | AmazonClientException ex) { Logger.getLogger(S3Util.class.getName()).log(Level.SEVERE, null, ex); } finally { try { if (bos != null) { bos.close(); } if (os != null) { os.close(); } if (is != null) { is.close(); } if (s != null) { s.close(); } if (byteInputStream != null) { byteInputStream.close(); } } catch (IOException ex) { Logger.getLogger(S3Util.class.getName()).log(Level.SEVERE, null, ex); } } return result; }
From source file:com.github.lucapino.sheetmaker.renderer.JavaTemplateRenderer.java
private ImagePanel drawTemplate(Element drawImageTemplateElement) throws Exception { // OutputImageSettings logger.info("reading ImageDrawTemlate attributes..."); Element outputImageSettingsElement = drawImageTemplateElement.getChild(OUTPUT_IMAGE_SETTINGS); String colorDepth = outputImageSettingsElement.getAttributeValue("ColorDepth"); String imageForat = outputImageSettingsElement.getAttributeValue("ImageFormat"); String jpegCompressionLevel = outputImageSettingsElement.getAttributeValue("JpegCompressionLevel"); String dpi = outputImageSettingsElement.getAttributeValue("Dpi"); logger.info("Reading Canvas attributes..."); // Canvas//from ww w . j a v a 2 s.co m Element canvasElement = drawImageTemplateElement.getChild(CANVAS); String autoSize = canvasElement.getAttributeValue("AutoSize"); String centerElements = canvasElement.getAttributeValue("CenterElements"); int width = Integer.valueOf(canvasElement.getAttributeValue("Width")); int height = Integer.valueOf(canvasElement.getAttributeValue("Height")); String fill = canvasElement.getAttributeValue("Fill"); // create image of specified dimensions logger.info("Creating working image..."); BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB); Graphics2D g2 = image.createGraphics(); g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); g2.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY); // Elements logger.info("Processing elements..."); Element elementsElement = drawImageTemplateElement.getChild("Elements"); for (Element element : elementsElement.getChildren()) { switch (element.getName()) { case "ImageElement": processImageElement(g2, element); break; case "TextElement": processTextElement(g2, element); break; } } return new ImagePanel(image); }