Example usage for java.awt.image BufferedImage TYPE_INT_RGB

List of usage examples for java.awt.image BufferedImage TYPE_INT_RGB

Introduction

In this page you can find the example usage for java.awt.image BufferedImage TYPE_INT_RGB.

Prototype

int TYPE_INT_RGB

To view the source code for java.awt.image BufferedImage TYPE_INT_RGB.

Click Source Link

Document

Represents an image with 8-bit RGB color components packed into integer pixels.

Usage

From source file:org.nekorp.workflow.desktop.servicio.reporte.orden.servicio.OrdenServicioDataFactory.java

private void generaImagenDamage(ShapeView fondo, List<DamageDetailsVB> danios, File outputfile, int width,
        int height) {
    try {/* w w  w.  j a  v  a  2 s. com*/
        Point contexto = new Point((width - fondo.getShapeWidth()) / 2, (height - fondo.getShapeHeight()) / 2);
        BufferedImage off_Image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        Graphics2D g2 = off_Image.createGraphics();
        g2.setColor(Color.WHITE);
        g2.fillRect(0, 0, width, height);
        AffineTransform saveXform = g2.getTransform();
        AffineTransform toCenterAt = new AffineTransform();
        toCenterAt.translate(contexto.getX(), contexto.getY());
        g2.transform(toCenterAt);
        fondo.paint(g2);
        g2.setTransform(saveXform);
        for (DamageDetailsVB x : danios) {
            DamageDetailGraphicsView obj = new DamageDetailGraphicsView();
            obj.setPosicion(new Point(x.getX(), x.getY()));
            obj.setContexto(contexto);
            if (x.getX() <= fondo.getShapeWidth() / 2) {
                if (x.getY() <= fondo.getShapeHeight() / 2) {
                    obj.setOrientacion(DamageDetailGraphicsView.SuperiorIzquierda);
                } else {
                    obj.setOrientacion(DamageDetailGraphicsView.InferiorIzquierda);
                }
            } else {
                if (x.getY() <= fondo.getShapeHeight() / 2) {
                    obj.setOrientacion(DamageDetailGraphicsView.SuperiorDerecha);
                } else {
                    obj.setOrientacion(DamageDetailGraphicsView.InferiorDerecha);
                }
            }
            obj.setCategoria(x.getCategoria());
            obj.setCaracteristica(x.getCaracteristica());
            obj.paint(g2);
        }
        saveJPG(off_Image, outputfile);
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

From source file:com.openkm.servlet.admin.StampServlet.java

/**
 * View text color/*  w w w  . ja  va 2s.  co  m*/
 */
private void textColor(Session session, HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException, DatabaseException {
    log.debug("textColor({}, {}, {})", new Object[] { session, request, response });
    int stId = WebUtils.getInt(request, "st_id");
    StampText st = StampTextDAO.findByPk(stId);
    BufferedImage bi = new BufferedImage(16, 16, BufferedImage.TYPE_INT_RGB);
    Graphics g = bi.getGraphics();
    g.setColor(Color.decode(st.getColor()));
    g.fillRect(0, 0, 16, 16);
    response.setContentType("image/jpeg");
    ImageIO.write(bi, "jpg", response.getOutputStream());
    log.debug("textColor: void");
}

From source file:com.funambol.foundation.util.MediaUtils.java

/**
 * Creates the thumbnail.//from w w  w .  j av a2  s .  c  o m
 *
 * @param imageFile the image file
 * @param thumbFile the empty thumbnail file
 * @param thumbX the width of the thumbnail
 * @param thumbY the height of the thumbnail
 * @param imageName the image file name with extension
 * @param tolerance the percentage of tolerance before creating a thumbnail
 * @return true is the thumbnail has been created, false otherwise
 * @throws IOException if an error occurs
 */
private static boolean createThumbnail(File imageFile, File thumbFile, int thumbX, int thumbY, String imageName,
        double tolerance) throws IOException {

    FileInputStream fileis = null;
    ImageInputStream imageis = null;

    Iterator readers = null;

    try {

        readers = ImageIO.getImageReadersByFormatName(imageName.substring(imageName.lastIndexOf('.') + 1));
        if (readers == null || (!readers.hasNext())) {
            throw new IOException("File not supported");
        }

        ImageReader reader = (ImageReader) readers.next();

        fileis = new FileInputStream(imageFile);
        imageis = ImageIO.createImageInputStream(fileis);
        reader.setInput(imageis, true);

        // Determines thumbnail height, width and quality
        int thumbWidth = thumbX;
        int thumbHeight = thumbY;

        double thumbRatio = (double) thumbWidth / (double) thumbHeight;
        int imageWidth = reader.getWidth(0);
        int imageHeight = reader.getHeight(0);

        //
        // Don't create the thumbnail if the original file is smaller
        // than required size increased by % tolerance
        //
        if (imageWidth <= (thumbWidth * (1 + tolerance / 100))
                && imageHeight <= (thumbHeight * (1 + tolerance / 100))) {

            return false;
        }

        double imageRatio = (double) imageWidth / (double) imageHeight;
        if (thumbRatio < imageRatio) {
            thumbHeight = (int) (thumbWidth / imageRatio);
        } else {
            thumbWidth = (int) (thumbHeight * imageRatio);
        }

        ImageReadParam param = reader.getDefaultReadParam();
        param.setSourceSubsampling(3, 3, 0, 0);

        BufferedImage bi = reader.read(0, param);

        Image thumb = bi.getScaledInstance(thumbWidth, thumbHeight, Image.SCALE_SMOOTH);

        BufferedImage thumbImage = new BufferedImage(thumbWidth, thumbHeight, BufferedImage.TYPE_INT_RGB);
        Graphics2D graphics2D = thumbImage.createGraphics();
        graphics2D.setRenderingHint(RenderingHints.KEY_INTERPOLATION,
                RenderingHints.VALUE_INTERPOLATION_BILINEAR);
        graphics2D.drawImage(thumb, 0, 0, thumbWidth, thumbHeight, null);

        FileOutputStream fileOutputStream = new FileOutputStream(thumbFile);
        ImageIO.write(thumbImage, "jpg", fileOutputStream);

        thumb.flush();
        thumbImage.flush();
        fileOutputStream.flush();
        fileOutputStream.close();
        graphics2D.dispose();

    } finally {
        if (fileis != null) {
            fileis.close();
        }
        if (imageis != null) {
            imageis.close();
        }
    }

    return true;
}

From source file:com.aimluck.eip.fileupload.util.FileuploadUtils.java

/**
 * ???/*from w  w w. ja  v  a  2 s .  c  om*/
 * 
 * @param imgfile
 * @param width
 * @param height
 * @return
 */
public static BufferedImage shrinkAndTrimImage(BufferedImage imgfile, int width, int height) {
    int iwidth = imgfile.getWidth();
    int iheight = imgfile.getHeight();
    double ratio = Math.max((double) width / (double) iwidth, (double) height / (double) iheight);

    int shrinkedWidth;
    int shrinkedHeight;

    if ((iwidth <= width) || (iheight < height)) {
        shrinkedWidth = iwidth;
        shrinkedHeight = iheight;
    } else {
        shrinkedWidth = (int) (iwidth * ratio);
        shrinkedHeight = (int) (iheight * ratio);
    }

    // ??
    Image targetImage = imgfile.getScaledInstance(shrinkedWidth, shrinkedHeight, Image.SCALE_AREA_AVERAGING);

    int w_size = targetImage.getWidth(null);
    int h_size = targetImage.getHeight(null);
    if (targetImage.getWidth(null) < width) {
        w_size = width;
    }
    if (targetImage.getHeight(null) < height) {
        h_size = height;
    }
    BufferedImage tmpImage = new BufferedImage(w_size, h_size, BufferedImage.TYPE_INT_RGB);
    Graphics2D g = tmpImage.createGraphics();
    g.setBackground(Color.WHITE);
    g.setColor(Color.WHITE);
    // ??????????????
    g.fillRect(0, 0, w_size, h_size);
    int diff_w = 0;
    int diff_h = 0;
    if (width > shrinkedWidth) {
        diff_w = (width - shrinkedWidth) / 2;
    }
    if (height > shrinkedHeight) {
        diff_h = (height - shrinkedHeight) / 2;
    }
    g.drawImage(targetImage, diff_w, diff_h, null);

    int _iwidth = tmpImage.getWidth();
    int _iheight = tmpImage.getHeight();
    BufferedImage _tmpImage;
    if (_iwidth > _iheight) {
        int diff = _iwidth - width;
        _tmpImage = tmpImage.getSubimage(diff / 2, 0, width, height);
    } else {
        int diff = _iheight - height;
        _tmpImage = tmpImage.getSubimage(0, diff / 2, width, height);
    }
    return _tmpImage;
}

From source file:org.geowebcache.service.wms.WMSTileFuser.java

protected void createCanvas() {
    // TODO take bgcolor and transparency from request into account
    // should move this into a separate function

    Color bgColor = null;//from w  w w.j  a  va2 s . c o m
    boolean transparent = true;

    if (layer instanceof WMSLayer) {
        WMSLayer wmsLayer = (WMSLayer) layer;
        int[] colorAr = wmsLayer.getBackgroundColor();

        if (colorAr != null) {
            bgColor = new Color(colorAr[0], colorAr[1], colorAr[2]);
        }
        transparent = wmsLayer.getTransparent();
    }

    int canvasType;
    if (bgColor == null && transparent
            && (outputFormat.supportsAlphaBit() || outputFormat.supportsAlphaChannel())) {
        canvasType = BufferedImage.TYPE_INT_ARGB;
    } else {
        canvasType = BufferedImage.TYPE_INT_RGB;
        if (bgColor == null) {
            bgColor = Color.WHITE;
        }
    }

    // Create the actual canvas and graphics object
    canvas = new BufferedImage(canvasSize[0], canvasSize[1], canvasType);
    gfx = (Graphics2D) canvas.getGraphics();

    if (bgColor != null) {
        gfx.setColor(bgColor);
        gfx.fillRect(0, 0, canvasSize[0], canvasSize[1]);
    }

    // Hints settings
    RenderingHints hintsTemp = HintsLevel.DEFAULT.getRenderingHints();

    if (hints != null) {
        hintsTemp = hints;
    }
    gfx.addRenderingHints(hintsTemp);
}

From source file:de.tuttas.restful.SchuelerManager.java

private BufferedImage createResizedCopy(Image originalImage, int scaledWidth, int scaledHeight,
        boolean preserveAlpha) {
    int imageType = preserveAlpha ? BufferedImage.TYPE_INT_RGB : BufferedImage.TYPE_INT_ARGB;
    BufferedImage scaledBI = new BufferedImage(scaledWidth, scaledHeight, imageType);
    Graphics2D g = scaledBI.createGraphics();
    if (preserveAlpha) {
        g.setComposite(AlphaComposite.Src);
    }/*  w  ww .  ja  v a 2  s. c o m*/
    g.drawImage(originalImage, 0, 0, scaledWidth, scaledHeight, null);
    g.dispose();
    return scaledBI;
}

From source file:view.FramePrincipal.java

private static BufferedImage createBufferedImage(String fileName) {
    BufferedImage image = null;//from w  w  w . j  a v a 2 s .c  o  m
    try {
        image = ImageIO.read(new File(fileName));
    } catch (IOException e) {
        return null;
    }

    int sizeX = image.getWidth();
    int sizeY = image.getHeight();

    BufferedImage result = new BufferedImage(sizeX, sizeY, BufferedImage.TYPE_INT_RGB);
    Graphics g = result.createGraphics();
    g.drawImage(image, 0, 0, null);
    g.dispose();
    return result;
}

From source file:com.github.lindenb.jvarkit.tools.misc.BamCmpCoverage.java

@Override
public Collection<Throwable> call() throws Exception {

    if (getOutputFile() == null) {
        return wrapException("output image file not defined");
    }//from   w  ww  .ja v  a 2s  . c o m

    if (this.imgageSize < 1) {
        return wrapException("Bad image size:" + this.imgageSize);
    }

    if (this.minDepth < 0) {
        return wrapException("Bad min depth : " + this.minDepth);
    }
    if (this.minDepth >= this.maxDepth) {
        return wrapException("Bad min<max depth : " + this.minDepth + "<" + this.maxDepth);
    }

    if (this.getBedFile() != null) {
        readBedFile(this.getBedFile());
    }

    if (regionStr != null && this.intervals != null) {
        return wrapException("bed and interval both defined.");
    }

    final SamRecordFilter filter = new SamRecordFilter() {
        @Override
        public boolean filterOut(SAMRecord first, SAMRecord second) {
            return filterOut(first);
        }

        @Override
        public boolean filterOut(SAMRecord rec) {
            if (rec.getReadUnmappedFlag())
                return true;
            if (rec.isSecondaryOrSupplementary())
                return true;
            if (rec.getDuplicateReadFlag())
                return true;
            if (rec.getNotPrimaryAlignmentFlag())
                return true;
            if (rec.getReadFailsVendorQualityCheckFlag())
                return true;
            if (rec.getMappingQuality() == 0)
                return true;
            /* ignore non-overlapping BED, already checked with QuertInterval 
            if( intervals!=null &&
               ! intervals.containsOverlapping(
               new Interval(rec.getReferenceName(),
             rec.getAlignmentStart(),
             rec.getAlignmentEnd()))
             )
               {
               return true;
               }
               */

            return false;
        }
    };
    Set<File> files = new HashSet<File>();
    try {

        SamReaderFactory srf = SamReaderFactory.makeDefault().validationStringency(ValidationStringency.SILENT);
        srf.disable(SamReaderFactory.Option.EAGERLY_DECODE);
        srf.disable(SamReaderFactory.Option.INCLUDE_SOURCE_IN_RECORDS);
        srf.disable(SamReaderFactory.Option.VALIDATE_CRC_CHECKSUMS);
        final List<String> args = this.getInputFiles();
        for (String arg : args) {
            File f = new File(arg);
            if (f.getName().endsWith(".list")) {
                LOG.info("Reading BAM list from " + f);
                BufferedReader in = IOUtils.openFileForBufferedReading(f);
                String line;
                while ((line = in.readLine()) != null) {
                    if (line.trim().isEmpty() || line.startsWith("#"))
                        continue;
                    files.add(new File(line));
                }
                in.close();
            } else {
                files.add(f);
            }
        }
        if (files.isEmpty()) {
            return wrapException("No BAM defined");
        }

        Comparator<SAMRecord> comparator = new Comparator<SAMRecord>() {
            @Override
            public int compare(SAMRecord samRecord1, SAMRecord samRecord2) {
                final int refIndex1 = samRecord1.getReferenceIndex();
                final int refIndex2 = samRecord2.getReferenceIndex();
                if (refIndex1 == -1) {
                    return (refIndex2 == -1 ? 0 : 1);
                } else if (refIndex2 == -1) {
                    return -1;
                }
                final int cmp = refIndex1 - refIndex2;
                if (cmp != 0) {
                    return cmp;
                }
                return samRecord1.getAlignmentStart() - samRecord2.getAlignmentStart();
            }
        };
        List<SamReader> readers = new ArrayList<SamReader>(files.size());
        List<CloseableIterator<SAMRecord>> iterators = new ArrayList<CloseableIterator<SAMRecord>>(
                files.size());

        Set<String> samples = new TreeSet<String>();
        SAMSequenceDictionary dict = null;

        /* will be initialized below once, if needed */
        QueryInterval queryIntervalArray[] = null;

        //scan samples names
        for (File bamFile : files) {
            SamReader r = srf.open(bamFile);
            readers.add(r);

            SAMFileHeader h = r.getFileHeader();
            if (h.getSortOrder() != SortOrder.coordinate) {
                r.close();
                return wrapException("file " + bamFile + " not sorted on coordinate");
            }
            if (dict == null) {
                dict = h.getSequenceDictionary();
            } else if (!SequenceUtil.areSequenceDictionariesEqual(dict, h.getSequenceDictionary())) {
                return wrapException("Found more than one dictint sequence dictionary");
            }

            //fill query interval once
            List<QueryInterval> queryIntervals = new ArrayList<>();
            if (regionStr != null && queryIntervalArray == null) {
                int colon = regionStr.indexOf(':');
                String chrom;
                int chromStart;
                int chromEnd;

                if (colon == -1) {
                    chrom = regionStr;
                } else {
                    chrom = regionStr.substring(0, colon);
                }

                SAMSequenceRecord ssr = dict.getSequence(chrom);
                if (ssr == null) {
                    return wrapException("Chromosome " + chrom + " not present in dictionary");
                }
                int hyphen = regionStr.indexOf('-', colon + 1);
                if (hyphen != -1) {
                    chromStart = Integer.parseInt(regionStr.substring(colon + 1, hyphen));
                    chromEnd = Integer.parseInt(regionStr.substring(hyphen + 1));
                } else {
                    chromStart = 0;
                    chromEnd = ssr.getSequenceLength() - 1;
                }
                if (chromStart < 0 || chromEnd < chromStart) {
                    return wrapException("bad position in " + regionStr);
                }

                queryIntervals.add(new QueryInterval(ssr.getSequenceIndex(), chromStart, chromEnd));
            }

            if (this.intervals != null && queryIntervalArray == null) {
                for (Interval interval : this.intervals.keySet()) {
                    SAMSequenceRecord ssr = dict.getSequence(interval.getContig());
                    if (ssr == null) {
                        return wrapException(
                                "Chromosome " + interval.getContig() + " not present in dictionary");
                    }
                    queryIntervals.add(
                            new QueryInterval(ssr.getSequenceIndex(), interval.getStart(), interval.getEnd()));
                }
            }

            if (!queryIntervals.isEmpty() && queryIntervalArray == null) {
                Collections.sort(queryIntervals);
                queryIntervalArray = queryIntervals.toArray(new QueryInterval[queryIntervals.size()]);
            }

            for (SAMReadGroupRecord rg : h.getReadGroups()) {
                String sample = rg.getSample();
                if (sample == null)
                    continue;
                samples.add(sample);
            }
            CloseableIterator<SAMRecord> reciterator = null;
            if (queryIntervalArray == null) {
                reciterator = r.iterator();
            } else {
                reciterator = r.query(queryIntervalArray, false);
            }

            reciterator = new FilteringIterator(reciterator, filter);
            iterators.add(reciterator);
        }
        //free GC
        queryIntervalArray = null;

        LOG.info("Samples:" + samples.size());
        for (String sample : samples) {
            this.sample2column.put(sample, this.sample2column.size());
        }

        //create merging sam-reader
        MergingSamRecordIterator iter = new MergingSamRecordIterator(comparator, iterators);

        //create image
        LOG.info("Creating image " + this.imgageSize + "x" + this.imgageSize);
        this.image = new BufferedImage(this.imgageSize, this.imgageSize, BufferedImage.TYPE_INT_RGB);
        Graphics2D g = this.image.createGraphics();
        this.marginWidth = this.imgageSize * 0.05;
        double drawingWidth = (this.imgageSize - 1) - marginWidth;
        this.sampleWidth = drawingWidth / samples.size();
        //g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
        g.setColor(Color.WHITE);
        g.fillRect(0, 0, this.imgageSize, this.imgageSize);
        g.setColor(Color.BLACK);
        Hershey hershey = new Hershey();
        for (String sample_x : samples) {
            double labelHeight = marginWidth;
            if (labelHeight > 50)
                labelHeight = 50;

            g.setColor(Color.BLACK);
            hershey.paint(g, sample_x, marginWidth + sample2column.get(sample_x) * sampleWidth,
                    marginWidth - labelHeight, sampleWidth * 0.9, labelHeight * 0.9);

            AffineTransform old = g.getTransform();
            AffineTransform tr = AffineTransform.getTranslateInstance(marginWidth,
                    marginWidth + sample2column.get(sample_x) * sampleWidth);
            tr.rotate(Math.PI / 2);
            g.setTransform(tr);
            hershey.paint(g, sample_x, 0.0, 0.0, sampleWidth * 0.9, labelHeight * 0.9); //g.drawString(this.tabixFile.getFile().getName(),0,0);
            g.setTransform(old);

            for (String sample_y : samples) {

                Rectangle2D rect = new Rectangle2D.Double(
                        marginWidth + sample2column.get(sample_x) * sampleWidth,
                        marginWidth + sample2column.get(sample_y) * sampleWidth, sampleWidth, sampleWidth);
                g.setColor(Color.BLUE);
                g.draw(new Line2D.Double(rect.getMinX(), rect.getMinY(), rect.getMaxX(), rect.getMaxY()));
                g.setColor(Color.BLACK);
                g.draw(rect);
            }
        }

        //ceate bit-array
        BitSampleMatrix bitMatrix = new BitSampleMatrix(samples.size());

        //preivous chrom
        //int prev_tid=-1;
        BufferedList<Depth> depthList = new BufferedList<Depth>();
        g.setColor(Color.BLACK);
        SAMSequenceDictionaryProgress progress = new SAMSequenceDictionaryProgress(dict);
        LOG.info("Scanning bams...");
        while (iter.hasNext()) {
            SAMRecord rec = iter.next();
            if (filter.filterOut(rec))
                continue;
            progress.watch(rec);

            SAMReadGroupRecord gr = rec.getReadGroup();
            if (gr == null)
                continue;
            String sample = gr.getSample();
            if (sample == null)
                continue;
            int sample_id = this.sample2column.get(sample);

            Cigar cigar = rec.getCigar();
            if (cigar == null)
                continue;
            int refPos = rec.getAlignmentStart();

            /* cleanup front pos */
            while (!depthList.isEmpty()) {
                Depth front = depthList.getFirst();

                if (front.tid != rec.getReferenceIndex().intValue() || front.pos < refPos) {
                    paint(bitMatrix, front);
                    depthList.removeFirst();
                    continue;
                } else {
                    break;
                }
            }

            for (CigarElement ce : cigar.getCigarElements()) {
                CigarOperator op = ce.getOperator();
                if (!op.consumesReferenceBases())
                    continue;
                if (op.consumesReadBases()) {
                    for (int i = 0; i < ce.getLength(); ++i) {
                        Depth depth = null;
                        int pos = refPos + i;

                        //ignore non-overlapping BED
                        if (this.intervals != null && !this.intervals
                                .containsOverlapping(new Interval(rec.getReferenceName(), pos, pos))) {
                            continue;
                        } else if (depthList.isEmpty()) {
                            depth = new Depth();
                            depth.pos = pos;
                            depth.tid = rec.getReferenceIndex();
                            depthList.add(depth);
                        } else if (depthList.getLast().pos < pos) {
                            Depth prev = depthList.getLast();

                            while (prev.pos < pos) {
                                depth = new Depth();
                                depth.pos = prev.pos + 1;
                                depth.tid = rec.getReferenceIndex();
                                depthList.add(depth);
                                prev = depth;
                            }
                            depth = prev;
                        }

                        else {
                            int lastPos = depthList.get(depthList.size() - 1).pos;
                            int distance = lastPos - pos;
                            int indexInList = (depthList.size() - 1) - (distance);
                            if (indexInList < 0) {
                                //can appen when BED declared and partially overlap the read
                                continue;
                            }

                            depth = depthList.get((depthList.size() - 1) - (distance));
                            if (depth.pos != pos) {
                                return wrapException(" " + pos + " vs " + depth.pos + " " + lastPos);
                            }
                        }
                        depth.depths[sample_id]++;
                    }
                }
                refPos += ce.getLength();
            }
        }
        while (!depthList.isEmpty()) {
            //paint(g,depthList.remove(0));
            paint(bitMatrix, depthList.remove(0));
        }
        progress.finish();
        iter.close();

        //paint bitset

        for (int x = 0; x < bitMatrix.n_samples; ++x) {
            for (int y = 0; y < bitMatrix.n_samples; ++y) {
                LOG.info("Painting...(" + x + "/" + y + ")");
                paint(g, bitMatrix.get(x, y));
            }
        }

        g.dispose();
        //close readers
        for (SamReader r : readers)
            r.close();

        //save file
        LOG.info("saving " + getOutputFile());
        if (getOutputFile().getName().toLowerCase().endsWith(".png")) {
            ImageIO.write(this.image, "PNG", getOutputFile());
        } else {
            ImageIO.write(this.image, "JPG", getOutputFile());
        }

        return Collections.emptyList();
    } catch (Exception err) {
        return wrapException(err);
    } finally {

    }
}

From source file:snapshot.java

public static Object respond(final RequestHeader header, serverObjects post, final serverSwitch env) {
    final Switchboard sb = (Switchboard) env;

    final serverObjects defaultResponse = new serverObjects();

    final boolean authenticated = sb.adminAuthenticated(header) >= 2;
    final String ext = header.get(HeaderFramework.CONNECTION_PROP_EXT, "");

    if (ext.isEmpty()) {
        throw new TemplateProcessingException(
                "Missing extension. Try with rss, xml, json, pdf, png or jpg." + ext,
                HttpStatus.SC_BAD_REQUEST);
    }//from   w w  w. j  a v  a 2s  .c o m

    if (ext.equals("rss")) {
        // create a report about the content of the snapshot directory
        if (!authenticated) {
            defaultResponse.authenticationRequired();
            return defaultResponse;
        }
        int maxcount = post == null ? 10 : post.getInt("maxcount", 10);
        int depthx = post == null ? -1 : post.getInt("depth", -1);
        Integer depth = depthx == -1 ? null : depthx;
        String orderx = post == null ? "ANY" : post.get("order", "ANY");
        Snapshots.Order order = Snapshots.Order.valueOf(orderx);
        String statex = post == null ? Transactions.State.INVENTORY.name()
                : post.get("state", Transactions.State.INVENTORY.name());
        Transactions.State state = Transactions.State.valueOf(statex);
        String host = post == null ? null : post.get("host");
        Map<String, Revisions> iddate = Transactions.select(host, depth, order, maxcount, state);
        // now select the URL from the index for these ids in iddate and make an RSS feed
        RSSFeed rssfeed = new RSSFeed(Integer.MAX_VALUE);
        rssfeed.setChannel(new RSSMessage("Snapshot list for host = " + host + ", depth = " + depth
                + ", order = " + order + ", maxcount = " + maxcount, "", ""));
        for (Map.Entry<String, Revisions> e : iddate.entrySet()) {
            try {
                DigestURL u = e.getValue().url == null ? sb.index.fulltext().getURL(e.getKey())
                        : new DigestURL(e.getValue().url);
                if (u == null)
                    continue;
                RSSMessage message = new RSSMessage(u.toNormalform(true), "", u, e.getKey());
                message.setPubDate(e.getValue().dates[0]);
                rssfeed.addMessage(message);
            } catch (IOException ee) {
                ConcurrentLog.logException(ee);
            }
        }
        byte[] rssBinary = UTF8.getBytes(rssfeed.toString());
        return new ByteArrayInputStream(rssBinary);
    }

    // for the following methods we (mostly) need an url or a url hash
    if (post == null)
        post = new serverObjects();
    final boolean xml = ext.equals("xml");
    final boolean pdf = ext.equals("pdf");
    if (pdf && !authenticated) {
        defaultResponse.authenticationRequired();
        return defaultResponse;
    }
    final boolean pngjpg = ext.equals("png") || ext.equals(DEFAULT_EXT);
    String urlhash = post.get("urlhash", "");
    String url = post.get("url", "");
    DigestURL durl = null;
    if (urlhash.length() == 0 && url.length() > 0) {
        try {
            durl = new DigestURL(url);
            urlhash = ASCII.String(durl.hash());
        } catch (MalformedURLException e) {
        }
    }
    if (durl == null && urlhash.length() > 0) {
        try {
            durl = sb.index.fulltext().getURL(urlhash);
        } catch (IOException e) {
            ConcurrentLog.logException(e);
        }
    }

    if (ext.equals("json")) {
        // command interface: view and change a transaction state, get metadata about transactions in the past
        String command = post.get("command", "metadata");
        String statename = post.get("state");
        JSONObject result = new JSONObject();
        try {
            if (command.equals("status")) {
                // return a status of the transaction archive
                JSONObject sizes = new JSONObject();
                for (Map.Entry<String, Integer> state : Transactions.sizes().entrySet())
                    sizes.put(state.getKey(), state.getValue());
                result.put("size", sizes);
            } else if (command.equals("list")) {
                if (!authenticated) {
                    defaultResponse.authenticationRequired();
                    return defaultResponse;
                }
                // return a status of the transaction archive
                String host = post.get("host");
                String depth = post.get("depth");
                int depthi = depth == null ? -1 : Integer.parseInt(depth);
                for (Transactions.State state : statename == null
                        ? new Transactions.State[] { Transactions.State.INVENTORY, Transactions.State.ARCHIVE }
                        : new Transactions.State[] { Transactions.State.valueOf(statename) }) {
                    if (host == null) {
                        JSONObject hostCountInventory = new JSONObject();
                        for (String h : Transactions.listHosts(state)) {
                            int size = Transactions.listIDsSize(h, depthi, state);
                            if (size > 0)
                                hostCountInventory.put(h, size);
                        }
                        result.put("count." + state.name(), hostCountInventory);
                    } else {
                        TreeMap<Integer, Collection<Revisions>> ids = Transactions.listIDs(host, depthi, state);
                        if (ids == null) {
                            result.put("result", "fail");
                            result.put("comment", "no entries for host " + host + " found");
                        } else {
                            for (Map.Entry<Integer, Collection<Revisions>> entry : ids.entrySet()) {
                                for (Revisions r : entry.getValue()) {
                                    try {
                                        JSONObject metadata = new JSONObject();
                                        DigestURL u = r.url != null ? new DigestURL(r.url)
                                                : sb.index.fulltext().getURL(r.urlhash);
                                        metadata.put("url", u == null ? "unknown" : u.toNormalform(true));
                                        metadata.put("dates", r.dates);
                                        assert r.depth == entry.getKey().intValue();
                                        metadata.put("depth", entry.getKey().intValue());
                                        result.put(r.urlhash, metadata);
                                    } catch (IOException e) {
                                    }
                                }
                            }
                        }
                    }
                }
            } else if (command.equals("commit")) {
                if (!authenticated) {
                    defaultResponse.authenticationRequired();
                    return defaultResponse;
                }
                Revisions r = Transactions.commit(urlhash);
                if (r != null) {
                    result.put("result", "success");
                    result.put("depth", r.depth);
                    result.put("url", r.url);
                    result.put("dates", r.dates);
                } else {
                    result.put("result", "fail");
                }
                result.put("urlhash", urlhash);
            } else if (command.equals("rollback")) {
                if (!authenticated) {
                    defaultResponse.authenticationRequired();
                    return defaultResponse;
                }
                Revisions r = Transactions.rollback(urlhash);
                if (r != null) {
                    result.put("result", "success");
                    result.put("depth", r.depth);
                    result.put("url", r.url);
                    result.put("dates", r.dates);
                } else {
                    result.put("result", "fail");
                }
                result.put("urlhash", urlhash);
            } else if (command.equals("metadata")) {
                try {
                    Revisions r;
                    Transactions.State state = statename == null || statename.length() == 0 ? null
                            : Transactions.State.valueOf(statename);
                    if (state == null) {
                        r = Transactions.getRevisions(Transactions.State.INVENTORY, urlhash);
                        if (r != null)
                            state = Transactions.State.INVENTORY;
                        r = Transactions.getRevisions(Transactions.State.ARCHIVE, urlhash);
                        if (r != null)
                            state = Transactions.State.ARCHIVE;
                    } else {
                        r = Transactions.getRevisions(state, urlhash);
                    }
                    if (r != null) {
                        JSONObject metadata = new JSONObject();
                        DigestURL u;
                        u = r.url != null ? new DigestURL(r.url) : sb.index.fulltext().getURL(r.urlhash);
                        metadata.put("url", u == null ? "unknown" : u.toNormalform(true));
                        metadata.put("dates", r.dates);
                        metadata.put("depth", r.depth);
                        metadata.put("state", state.name());
                        result.put(r.urlhash, metadata);
                    }
                } catch (IOException | IllegalArgumentException e) {
                }
            }
        } catch (JSONException e) {
            ConcurrentLog.logException(e);
        }
        String json = result.toString();
        if (post.containsKey("callback"))
            json = post.get("callback") + "([" + json + "]);";
        return new ByteArrayInputStream(UTF8.getBytes(json));
    }

    // for the following methods we always need the durl to fetch data
    if (durl == null) {
        throw new TemplateMissingParameterException("Missing valid url or urlhash parameter");
    }

    if (xml) {
        Collection<File> xmlSnapshots = Transactions.findPaths(durl, "xml", Transactions.State.ANY);
        File xmlFile = null;
        if (xmlSnapshots.isEmpty()) {
            throw new TemplateProcessingException("Could not find the xml snapshot file.",
                    HttpStatus.SC_NOT_FOUND);
        }
        xmlFile = xmlSnapshots.iterator().next();
        try {
            byte[] xmlBinary = FileUtils.read(xmlFile);
            return new ByteArrayInputStream(xmlBinary);
        } catch (final IOException e) {
            ConcurrentLog.logException(e);
            throw new TemplateProcessingException("Could not read the xml snapshot file.");
        }
    }

    if (pdf || pngjpg) {
        Collection<File> pdfSnapshots = Transactions.findPaths(durl, "pdf", Transactions.State.INVENTORY);
        File pdfFile = null;
        if (pdfSnapshots.isEmpty()) {
            // if the client is authenticated, we create the pdf on the fly!
            if (!authenticated) {
                throw new TemplateProcessingException(
                        "Could not find the pdf snapshot file. You must be authenticated to generate one on the fly.",
                        HttpStatus.SC_NOT_FOUND);
            }
            SolrDocument sd = sb.index.fulltext().getMetadata(durl.hash());
            boolean success = false;
            if (sd == null) {
                success = Transactions.store(durl, new Date(), 99, false, true,
                        sb.getConfigBool(SwitchboardConstants.PROXY_TRANSPARENT_PROXY, false)
                                ? "http://127.0.0.1:" + sb.getConfigInt(SwitchboardConstants.SERVER_PORT, 8090)
                                : null,
                        sb.getConfig("crawler.http.acceptLanguage", null));
            } else {
                SolrInputDocument sid = sb.index.fulltext().getDefaultConfiguration().toSolrInputDocument(sd);
                success = Transactions.store(sid, false, true, true,
                        sb.getConfigBool(SwitchboardConstants.PROXY_TRANSPARENT_PROXY, false)
                                ? "http://127.0.0.1:" + sb.getConfigInt(SwitchboardConstants.SERVER_PORT, 8090)
                                : null,
                        sb.getConfig("crawler.http.acceptLanguage", null));
            }
            if (success) {
                pdfSnapshots = Transactions.findPaths(durl, "pdf", Transactions.State.ANY);
                if (!pdfSnapshots.isEmpty()) {
                    pdfFile = pdfSnapshots.iterator().next();
                }
            }
        } else {
            pdfFile = pdfSnapshots.iterator().next();
        }
        if (pdfFile == null) {
            throw new TemplateProcessingException(
                    "Could not find the pdf snapshot file and could not generate one on the fly.",
                    HttpStatus.SC_NOT_FOUND);
        }
        if (pdf) {
            try {
                byte[] pdfBinary = FileUtils.read(pdfFile);
                return new ByteArrayInputStream(pdfBinary);
            } catch (final IOException e) {
                ConcurrentLog.logException(e);
                throw new TemplateProcessingException("Could not read the pdf snapshot file.");
            }
        }

        if (pngjpg) {
            int width = Math.min(post.getInt("width", DEFAULT_WIDTH), DEFAULT_WIDTH);
            int height = Math.min(post.getInt("height", DEFAULT_HEIGHT), DEFAULT_HEIGHT);
            String imageFileStub = pdfFile.getAbsolutePath();
            imageFileStub = imageFileStub.substring(0, imageFileStub.length() - 3); // cut off extension
            File imageFile = new File(imageFileStub + DEFAULT_WIDTH + "." + DEFAULT_HEIGHT + "." + ext);
            if (!imageFile.exists() && authenticated) {
                if (!Html2Image.pdf2image(pdfFile, imageFile, DEFAULT_WIDTH, DEFAULT_HEIGHT, DEFAULT_DENSITY,
                        DEFAULT_QUALITY)) {
                    throw new TemplateProcessingException(
                            "Could not generate the " + ext + " image snapshot file.");
                }
            }
            if (!imageFile.exists()) {
                throw new TemplateProcessingException(
                        "Could not find the " + ext
                                + " image snapshot file. You must be authenticated to generate one on the fly.",
                        HttpStatus.SC_NOT_FOUND);
            }
            if (width == DEFAULT_WIDTH && height == DEFAULT_HEIGHT) {
                try {
                    byte[] imageBinary = FileUtils.read(imageFile);
                    return new ByteArrayInputStream(imageBinary);
                } catch (final IOException e) {
                    ConcurrentLog.logException(e);
                    throw new TemplateProcessingException(
                            "Could not read the " + ext + " image snapshot file.");
                }
            }
            // lets read the file and scale
            Image image;
            try {
                image = ImageParser.parse(imageFile.getAbsolutePath(), FileUtils.read(imageFile));
                if (image == null) {
                    throw new TemplateProcessingException(
                            "Could not parse the " + ext + " image snapshot file.");
                }
                final Image scaled = image.getScaledInstance(width, height, Image.SCALE_AREA_AVERAGING);
                final MediaTracker mediaTracker = new MediaTracker(new Container());
                mediaTracker.addImage(scaled, 0);
                try {
                    mediaTracker.waitForID(0);
                } catch (final InterruptedException e) {
                }

                /*
                 * Ensure there is no alpha component on the ouput image, as it is pointless
                 * here and it is not well supported by the JPEGImageWriter from OpenJDK
                 */
                BufferedImage scaledBufferedImg = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
                scaledBufferedImg.createGraphics().drawImage(scaled, 0, 0, width, height, null);
                return new EncodedImage(scaledBufferedImg, ext, true);
            } catch (final IOException e) {
                ConcurrentLog.logException(e);
                throw new TemplateProcessingException("Could not scale the " + ext + " image snapshot file.");
            }

        }
    }

    throw new TemplateProcessingException(
            "Unsupported extension : " + ext + ". Try with rss, xml, json, pdf, png or jpg.",
            HttpStatus.SC_BAD_REQUEST);
}

From source file:net.sf.ginp.browser.FolderManagerImpl.java

void makeThumbImage(final File origPicture, final String thumbFileName, final int maxThumbSize) {
    if (log.isDebugEnabled()) {
        log.debug("makeThumbImage: origFileName=" + origPicture.getAbsolutePath() + " thumbFileName="
                + thumbFileName + " maxThumbSize=" + maxThumbSize);
    }/*  w w  w .j  a v  a  2  s  .  c o  m*/

    // Only jpegs supported.
    if ((origPicture.getName().toLowerCase()).endsWith(".jpg")
            || (origPicture.getName().toLowerCase()).endsWith(".jpeg")) {
        try {
            // thumb it.
            JPEGImageDecoder dc = JPEGCodec.createJPEGDecoder((new FileInputStream(origPicture)));
            BufferedImage origImage = dc.decodeAsBufferedImage();
            int origHeight = origImage.getHeight(null);
            int origWidth = origImage.getWidth(null);
            int scaledW = 0;
            int scaledH = 0;
            double scale = 1.0;

            if (origHeight < origWidth) {
                scale = (double) maxThumbSize / (double) origWidth;
            } else {
                scale = (double) maxThumbSize / (double) origHeight;
            }

            scaledW = (int) (scale * origWidth);
            scaledH = (int) (scale * origHeight);

            //AffineTransform  at  = new AffineTransform();
            AffineTransform tx;
            AffineTransformOp af;
            JPEGImageEncoder encoder;
            BufferedImage outImage;

            outImage = new BufferedImage(scaledW, scaledH, BufferedImage.TYPE_INT_RGB);
            tx = new AffineTransform();
            tx.scale(scale, scale);
            af = new AffineTransformOp(tx, null);
            af.filter(origImage, outImage);

            File ginpFolder = new File(
                    thumbFileName.substring(0, thumbFileName.lastIndexOf("/.ginp")) + "/.ginp");

            if (!(ginpFolder.exists())) {
                ginpFolder.mkdir();
            }

            encoder = JPEGCodec.createJPEGEncoder(new FileOutputStream(thumbFileName));
            encoder.encode(outImage);
        } catch (Exception e) {
            log.error("Error Makeing Thumb Image " + thumbFileName, e);
        }
    }
}