Example usage for java.awt.image BufferedImage getGraphics

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

Introduction

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

Prototype

public java.awt.Graphics getGraphics() 

Source Link

Document

This method returns a Graphics2D , but is here for backwards compatibility.

Usage

From source file:au.org.ala.biocache.web.WMSController.java

@RequestMapping(value = { "/ogc/legendGraphic" }, method = RequestMethod.GET)
public void getLegendGraphic(@RequestParam(value = "ENV", required = false, defaultValue = "") String env,
        @RequestParam(value = "STYLE", required = false, defaultValue = "8b0000;opacity=1;size=5") String style,
        @RequestParam(value = "WIDTH", required = false, defaultValue = "30") Integer width,
        @RequestParam(value = "HEIGHT", required = false, defaultValue = "20") Integer height,
        HttpServletRequest request, HttpServletResponse response) throws Exception {

    try {/*from w  w  w .jav a 2 s .  c o  m*/
        if (StringUtils.trimToNull(env) == null && StringUtils.trimToNull(style) == null) {
            style = "8b0000;opacity=1;size=5";
        }

        WmsEnv wmsEnv = new WmsEnv(env, style);
        BufferedImage img = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
        Graphics2D g = (Graphics2D) img.getGraphics();
        int size = width > height ? height : width;
        Paint fill = new Color(wmsEnv.colour | wmsEnv.alpha << 24);
        g.setPaint(fill);
        g.fillOval(0, 0, size, size);
        OutputStream out = response.getOutputStream();
        logger.debug("WMS - GetLegendGraphic requested : " + request.getQueryString());
        response.setContentType("image/png");
        ImageIO.write(img, "png", out);
        out.close();
    } catch (Exception e) {
        logger.error(e.getMessage(), e);
    }
}

From source file:au.org.ala.biocache.web.WMSController.java

/**
 * Method that produces the downloadable map integrated in AVH/OZCAM/Biocache.
 *
 * @param requestParams/*from  www. j  av a  2 s  . c  o m*/
 * @param format
 * @param extents
 * @param widthMm
 * @param pointRadiusMm
 * @param pradiusPx
 * @param pointColour
 * @param pointOpacity
 * @param baselayer
 * @param scale
 * @param dpi
 * @param outlinePoints
 * @param outlineColour
 * @param fileName
 * @param request
 * @param response
 * @throws Exception
 */
@RequestMapping(value = { "/webportal/wms/image", "/mapping/wms/image" }, method = RequestMethod.GET)
public void generatePublicationMap(SpatialSearchRequestParams requestParams,
        @RequestParam(value = "format", required = false, defaultValue = "jpg") String format,
        @RequestParam(value = "extents", required = true) String extents,
        @RequestParam(value = "widthmm", required = false, defaultValue = "60") Double widthMm,
        @RequestParam(value = "pradiusmm", required = false, defaultValue = "2") Double pointRadiusMm,
        @RequestParam(value = "pradiuspx", required = false) Integer pradiusPx,
        @RequestParam(value = "pcolour", required = false, defaultValue = "FF0000") String pointColour,
        @RequestParam(value = "popacity", required = false, defaultValue = "0.8") Double pointOpacity,
        @RequestParam(value = "baselayer", required = false, defaultValue = "world") String baselayer,
        @RequestParam(value = "scale", required = false, defaultValue = "off") String scale,
        @RequestParam(value = "dpi", required = false, defaultValue = "300") Integer dpi,
        @RequestParam(value = "outline", required = true, defaultValue = "false") boolean outlinePoints,
        @RequestParam(value = "outlineColour", required = true, defaultValue = "#000000") String outlineColour,
        @RequestParam(value = "fileName", required = false) String fileName, HttpServletRequest request,
        HttpServletResponse response) throws Exception {

    String[] bb = extents.split(",");

    double long1 = Double.parseDouble(bb[0]);
    double lat1 = Double.parseDouble(bb[1]);
    double long2 = Double.parseDouble(bb[2]);
    double lat2 = Double.parseDouble(bb[3]);

    if (lat1 <= -90) {
        lat1 = -89.999;
    }
    if (lat2 >= 90) {
        lat2 = 89.999;
    }

    int pminx = convertLngToPixel(long1);
    int pminy = convertLatToPixel(lat1);
    int pmaxx = convertLngToPixel(long2);
    int pmaxy = convertLatToPixel(lat2);

    int width = (int) ((dpi / 25.4) * widthMm);
    int height = (int) Math.round(width * ((pminy - pmaxy) / (double) (pmaxx - pminx)));

    if (height * width > MAX_IMAGE_PIXEL_COUNT) {
        String errorMessage = "Image size in pixels " + width + "x" + height + " exceeds "
                + MAX_IMAGE_PIXEL_COUNT + " pixels.  Make the image smaller";
        response.sendError(response.SC_NOT_ACCEPTABLE, errorMessage);
        throw new Exception(errorMessage);
    }

    int pointSize = -1;
    if (pradiusPx != null) {
        pointSize = (int) pradiusPx;
    } else {
        pointSize = (int) ((dpi / 25.4) * pointRadiusMm);
    }

    double[] boundingBox = transformBbox4326To900913(Double.parseDouble(bb[0]), Double.parseDouble(bb[1]),
            Double.parseDouble(bb[2]), Double.parseDouble(bb[3]));

    //"http://biocache.ala.org.au/ws/webportal/wms/reflect?
    //q=macropus&ENV=color%3Aff0000%3Bname%3Acircle%3Bsize%3A3%3Bopacity%3A1
    //&BBOX=12523443.0512,-2504688.2032,15028131.5936,0.33920000120997&WIDTH=256&HEIGHT=256");
    String speciesAddress = baseWsUrl + "/ogc/wms/reflect?" + "ENV=color%3A" + pointColour
            + "%3Bname%3Acircle%3Bsize%3A" + pointSize + "%3Bopacity%3A" + pointOpacity + "&BBOX="
            + boundingBox[0] + "," + boundingBox[1] + "," + boundingBox[2] + "," + boundingBox[3] + "&WIDTH="
            + width + "&HEIGHT=" + height + "&OUTLINE=" + outlinePoints + "&OUTLINECOLOUR=" + outlineColour
            + "&" + request.getQueryString();

    URL speciesURL = new URL(speciesAddress);
    BufferedImage speciesImage = ImageIO.read(speciesURL);

    //"http://spatial.ala.org.au/geoserver/wms/reflect?
    //LAYERS=ALA%3Aworld&SERVICE=WMS&VERSION=1.1.1&REQUEST=GetMap&STYLES=
    //&FORMAT=image%2Fjpeg&SRS=EPSG%3A900913&BBOX=12523443.0512,-1252343.932,13775787.3224,0.33920000004582&WIDTH=256&HEIGHT=256"
    String layout = "";
    if (!scale.equals("off")) {
        layout += "layout:scale";
    }
    String basemapAddress = geoserverUrl + "/wms/reflect?" + "LAYERS=ALA%3A" + baselayer
            + "&SERVICE=WMS&VERSION=1.1.1&REQUEST=GetMap&STYLES=" + "&FORMAT=image%2Fpng&SRS=EPSG%3A900913" //specify the mercator projection
            + "&BBOX=" + boundingBox[0] + "," + boundingBox[1] + "," + boundingBox[2] + "," + boundingBox[3]
            + "&WIDTH=" + width + "&HEIGHT=" + height + "&OUTLINE=" + outlinePoints + "&format_options=dpi:"
            + dpi + ";" + layout;

    BufferedImage basemapImage = ImageIO.read(new URL(basemapAddress));

    BufferedImage img = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
    Graphics2D combined = (Graphics2D) img.getGraphics();

    combined.drawImage(basemapImage, 0, 0, Color.WHITE, null);
    //combined.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, pointOpacity.floatValue()));
    combined.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 1.0f));
    combined.drawImage(speciesImage, null, 0, 0);
    combined.dispose();

    //if filename supplied, force a download
    if (fileName != null) {
        response.setContentType("application/octet-stream");
        response.setHeader("Content-Description", "File Transfer");
        response.setHeader("Content-Disposition", "attachment; filename=" + fileName);
        response.setHeader("Content-Transfer-Encoding", "binary");
    } else if (format.equalsIgnoreCase("png")) {
        response.setContentType("image/png");
    } else {
        response.setContentType("image/jpeg");
    }

    if (format.equalsIgnoreCase("png")) {
        OutputStream os = response.getOutputStream();
        ImageIO.write(img, format, os);
        os.close();
    } else {
        //handle jpeg + BufferedImage.TYPE_INT_ARGB
        BufferedImage img2;
        Graphics2D c2;
        (c2 = (Graphics2D) (img2 = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB)).getGraphics())
                .drawImage(img, 0, 0, Color.WHITE, null);
        c2.dispose();
        OutputStream os = response.getOutputStream();
        ImageIO.write(img2, format, os);
        os.close();
    }
}

From source file:net.pms.dlna.DLNAMediaInfo.java

public void parse(InputFile inputFile, Format ext, int type, boolean thumbOnly) {
    int i = 0;//from   w  ww.  j a  v a2 s.c om

    while (isParsing()) {
        if (i == 5) {
            setMediaparsed(true);
            break;
        }

        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
        }

        i++;
    }

    if (isMediaparsed()) {
        return;
    }

    if (inputFile != null) {
        if (inputFile.getFile() != null) {
            setSize(inputFile.getFile().length());
        } else {
            setSize(inputFile.getSize());
        }

        ProcessWrapperImpl pw = null;
        boolean ffmpeg_parsing = true;

        if (type == Format.AUDIO || ext instanceof AudioAsVideo) {
            ffmpeg_parsing = false;
            DLNAMediaAudio audio = new DLNAMediaAudio();

            if (inputFile.getFile() != null) {
                try {
                    AudioFile af = AudioFileIO.read(inputFile.getFile());
                    AudioHeader ah = af.getAudioHeader();

                    if (ah != null && !thumbOnly) {
                        int length = ah.getTrackLength();
                        int rate = ah.getSampleRateAsNumber();

                        if (ah.getEncodingType().toLowerCase().contains("flac 24")) {
                            audio.setBitsperSample(24);
                        }

                        audio.setSampleFrequency("" + rate);
                        setDuration((double) length);
                        setBitrate((int) ah.getBitRateAsNumber());
                        audio.getAudioProperties().setNumberOfChannels(2);

                        if (ah.getChannels() != null && ah.getChannels().toLowerCase().contains("mono")) {
                            audio.getAudioProperties().setNumberOfChannels(1);
                        } else if (ah.getChannels() != null
                                && ah.getChannels().toLowerCase().contains("stereo")) {
                            audio.getAudioProperties().setNumberOfChannels(2);
                        } else if (ah.getChannels() != null) {
                            audio.getAudioProperties().setNumberOfChannels(Integer.parseInt(ah.getChannels()));
                        }

                        audio.setCodecA(ah.getEncodingType().toLowerCase());

                        if (audio.getCodecA().contains("(windows media")) {
                            audio.setCodecA(audio.getCodecA()
                                    .substring(0, audio.getCodecA().indexOf("(windows media")).trim());
                        }
                    }

                    Tag t = af.getTag();

                    if (t != null) {
                        if (t.getArtworkList().size() > 0) {
                            setThumb(t.getArtworkList().get(0).getBinaryData());
                        } else {
                            if (configuration.getAudioThumbnailMethod() > 0) {
                                setThumb(CoverUtil.get().getThumbnailFromArtistAlbum(
                                        configuration.getAudioThumbnailMethod() == 1 ? CoverUtil.AUDIO_AMAZON
                                                : CoverUtil.AUDIO_DISCOGS,
                                        audio.getArtist(), audio.getAlbum()));
                            }
                        }

                        if (!thumbOnly) {
                            audio.setAlbum(t.getFirst(FieldKey.ALBUM));
                            audio.setArtist(t.getFirst(FieldKey.ARTIST));
                            audio.setSongname(t.getFirst(FieldKey.TITLE));
                            String y = t.getFirst(FieldKey.YEAR);

                            try {
                                if (y.length() > 4) {
                                    y = y.substring(0, 4);
                                }
                                audio.setYear(Integer.parseInt(((y != null && y.length() > 0) ? y : "0")));
                                y = t.getFirst(FieldKey.TRACK);
                                audio.setTrack(Integer.parseInt(((y != null && y.length() > 0) ? y : "1")));
                                audio.setGenre(t.getFirst(FieldKey.GENRE));
                            } catch (Throwable e) {
                                logger.debug("Error parsing unimportant metadata: " + e.getMessage());
                            }
                        }
                    }
                } catch (Throwable e) {
                    logger.debug("Error parsing audio file: {} - {}", e.getMessage(),
                            e.getCause() != null ? e.getCause().getMessage() : "");
                    ffmpeg_parsing = false;
                }

                if (audio.getSongname() == null || audio.getSongname().length() == 0) {
                    audio.setSongname(inputFile.getFile().getName());
                }

                if (!ffmpeg_parsing) {
                    getAudioTracksList().add(audio);
                }
            }
        }

        if (type == Format.IMAGE && inputFile.getFile() != null) {
            try {
                ffmpeg_parsing = false;
                ImageInfo info = Sanselan.getImageInfo(inputFile.getFile());
                setWidth(info.getWidth());
                setHeight(info.getHeight());
                setBitsPerPixel(info.getBitsPerPixel());
                String formatName = info.getFormatName();

                if (formatName.startsWith("JPEG")) {
                    setCodecV("jpg");
                    IImageMetadata meta = Sanselan.getMetadata(inputFile.getFile());

                    if (meta != null && meta instanceof JpegImageMetadata) {
                        JpegImageMetadata jpegmeta = (JpegImageMetadata) meta;
                        TiffField tf = jpegmeta.findEXIFValue(TiffConstants.EXIF_TAG_MODEL);

                        if (tf != null) {
                            setModel(tf.getStringValue().trim());
                        }

                        tf = jpegmeta.findEXIFValue(TiffConstants.EXIF_TAG_EXPOSURE_TIME);
                        if (tf != null) {
                            setExposure((int) (1000 * tf.getDoubleValue()));
                        }

                        tf = jpegmeta.findEXIFValue(TiffConstants.EXIF_TAG_ORIENTATION);
                        if (tf != null) {
                            setOrientation(tf.getIntValue());
                        }

                        tf = jpegmeta.findEXIFValue(TiffConstants.EXIF_TAG_ISO);
                        if (tf != null) {
                            // Galaxy Nexus jpg pictures may contain multiple values, take the first
                            int[] isoValues = tf.getIntArrayValue();
                            setIso(isoValues[0]);
                        }
                    }
                } else if (formatName.startsWith("PNG")) {
                    setCodecV("png");
                } else if (formatName.startsWith("GIF")) {
                    setCodecV("gif");
                } else if (formatName.startsWith("TIF")) {
                    setCodecV("tiff");
                }

                setContainer(getCodecV());
            } catch (Throwable e) {
                logger.info("Error parsing image ({}) with Sanselan, switching to FFmpeg.",
                        inputFile.getFile().getAbsolutePath());
            }
        }

        if (configuration.getImageThumbnailsEnabled() && type != Format.VIDEO && type != Format.AUDIO) {
            try {
                File thumbDir = new File(configuration.getTempFolder(), THUMBNAIL_DIRECTORY_NAME);

                logger.trace("Generating thumbnail for: {}", inputFile.getFile().getAbsolutePath());

                if (!thumbDir.exists() && !thumbDir.mkdirs()) {
                    logger.warn("Could not create thumbnail directory: {}", thumbDir.getAbsolutePath());
                } else {
                    File thumbFile = new File(thumbDir, inputFile.getFile().getName() + ".jpg");
                    String thumbFilename = thumbFile.getAbsolutePath();

                    logger.trace("Creating (temporary) thumbnail: {}", thumbFilename);

                    // Create the thumbnail image using the Thumbnailator library
                    final Builder<File> thumbnail = Thumbnails.of(inputFile.getFile());
                    thumbnail.size(320, 180);
                    thumbnail.outputFormat("jpg");
                    thumbnail.outputQuality(1.0f);

                    try {
                        thumbnail.toFile(thumbFilename);
                    } catch (IIOException e) {
                        logger.debug("Error generating thumbnail for: " + inputFile.getFile().getName());
                        logger.debug("The full error was: " + e);
                    }

                    File jpg = new File(thumbFilename);

                    if (jpg.exists()) {
                        InputStream is = new FileInputStream(jpg);
                        int sz = is.available();

                        if (sz > 0) {
                            setThumb(new byte[sz]);
                            is.read(getThumb());
                        }

                        is.close();

                        if (!jpg.delete()) {
                            jpg.deleteOnExit();
                        }
                    }
                }
            } catch (UnsupportedFormatException ufe) {
                logger.debug("Thumbnailator does not support the format of {}: {}",
                        inputFile.getFile().getAbsolutePath(), ufe.getMessage());
            } catch (Exception e) {
                logger.debug("Thumbnailator could not generate a thumbnail for: {}",
                        inputFile.getFile().getAbsolutePath(), e);
            }
        }

        if (ffmpeg_parsing) {
            if (!thumbOnly || !configuration.isUseMplayerForVideoThumbs()) {
                pw = getFFmpegThumbnail(inputFile);
            }

            String input = "-";
            boolean dvrms = false;

            if (inputFile.getFile() != null) {
                input = ProcessUtil.getShortFileNameIfWideChars(inputFile.getFile().getAbsolutePath());
                dvrms = inputFile.getFile().getAbsolutePath().toLowerCase().endsWith("dvr-ms");
            }

            if (!ffmpeg_failure && !thumbOnly) {
                if (input.equals("-")) {
                    input = "pipe:";
                }

                boolean matchs = false;
                ArrayList<String> lines = (ArrayList<String>) pw.getResults();
                int langId = 0;
                int subId = 0;
                ListIterator<String> FFmpegMetaData = lines.listIterator();

                for (String line : lines) {
                    FFmpegMetaData.next();
                    line = line.trim();
                    if (line.startsWith("Output")) {
                        matchs = false;
                    } else if (line.startsWith("Input")) {
                        if (line.indexOf(input) > -1) {
                            matchs = true;
                            setContainer(line.substring(10, line.indexOf(",", 11)).trim());
                        } else {
                            matchs = false;
                        }
                    } else if (matchs) {
                        if (line.indexOf("Duration") > -1) {
                            StringTokenizer st = new StringTokenizer(line, ",");
                            while (st.hasMoreTokens()) {
                                String token = st.nextToken().trim();
                                if (token.startsWith("Duration: ")) {
                                    String durationStr = token.substring(10);
                                    int l = durationStr.substring(durationStr.indexOf(".") + 1).length();
                                    if (l < 4) {
                                        durationStr = durationStr + "00".substring(0, 3 - l);
                                    }
                                    if (durationStr.indexOf("N/A") > -1) {
                                        setDuration(null);
                                    } else {
                                        setDuration(parseDurationString(durationStr));
                                    }
                                } else if (token.startsWith("bitrate: ")) {
                                    String bitr = token.substring(9);
                                    int spacepos = bitr.indexOf(" ");
                                    if (spacepos > -1) {
                                        String value = bitr.substring(0, spacepos);
                                        String unit = bitr.substring(spacepos + 1);
                                        setBitrate(Integer.parseInt(value));
                                        if (unit.equals("kb/s")) {
                                            setBitrate(1024 * getBitrate());
                                        }
                                        if (unit.equals("mb/s")) {
                                            setBitrate(1048576 * getBitrate());
                                        }
                                    }
                                }
                            }
                        } else if (line.indexOf("Audio:") > -1) {
                            StringTokenizer st = new StringTokenizer(line, ",");
                            int a = line.indexOf("(");
                            int b = line.indexOf("):", a);
                            DLNAMediaAudio audio = new DLNAMediaAudio();
                            audio.setId(langId++);
                            if (a > -1 && b > a) {
                                audio.setLang(line.substring(a + 1, b));
                            } else {
                                audio.setLang(DLNAMediaLang.UND);
                            }

                            // Get TS IDs
                            a = line.indexOf("[0x");
                            b = line.indexOf("]", a);
                            if (a > -1 && b > a + 3) {
                                String idString = line.substring(a + 3, b);
                                try {
                                    audio.setId(Integer.parseInt(idString, 16));
                                } catch (NumberFormatException nfe) {
                                    logger.debug("Error parsing Stream ID: " + idString);
                                }
                            }

                            while (st.hasMoreTokens()) {
                                String token = st.nextToken().trim();
                                Integer nChannels;

                                if (token.startsWith("Stream")) {
                                    audio.setCodecA(token.substring(token.indexOf("Audio: ") + 7));
                                } else if (token.endsWith("Hz")) {
                                    audio.setSampleFrequency(token.substring(0, token.indexOf("Hz")).trim());
                                } else if ((nChannels = audioChannelLayout.get(token)) != null) {
                                    audio.getAudioProperties().setNumberOfChannels(nChannels);
                                } else if (token.matches("\\d+(?:\\s+channels?)")) { // implicitly anchored at both ends e.g. ^ ... $
                                    // setNumberOfChannels(String) parses the number out of the string
                                    audio.getAudioProperties().setNumberOfChannels(token);
                                } else if (token.equals("s32")) {
                                    audio.setBitsperSample(32);
                                } else if (token.equals("s24")) {
                                    audio.setBitsperSample(24);
                                } else if (token.equals("s16")) {
                                    audio.setBitsperSample(16);
                                }
                            }
                            int FFmpegMetaDataNr = FFmpegMetaData.nextIndex();

                            if (FFmpegMetaDataNr > -1) {
                                line = lines.get(FFmpegMetaDataNr);
                            }

                            if (line.indexOf("Metadata:") > -1) {
                                FFmpegMetaDataNr = FFmpegMetaDataNr + 1;
                                line = lines.get(FFmpegMetaDataNr);
                                while (line.indexOf("      ") == 0) {
                                    if (line.toLowerCase().indexOf("title           :") > -1) {
                                        int aa = line.indexOf(": ");
                                        int bb = line.length();
                                        if (aa > -1 && bb > aa) {
                                            audio.setFlavor(line.substring(aa + 2, bb));
                                            break;
                                        }
                                    } else {
                                        FFmpegMetaDataNr = FFmpegMetaDataNr + 1;
                                        line = lines.get(FFmpegMetaDataNr);
                                    }
                                }
                            }

                            getAudioTracksList().add(audio);
                        } else if (line.indexOf("Video:") > -1) {
                            StringTokenizer st = new StringTokenizer(line, ",");
                            while (st.hasMoreTokens()) {
                                String token = st.nextToken().trim();
                                if (token.startsWith("Stream")) {
                                    setCodecV(token.substring(token.indexOf("Video: ") + 7));
                                } else if ((token.indexOf("tbc") > -1 || token.indexOf("tb(c)") > -1)) {
                                    // A/V sync issues with newest FFmpeg, due to the new tbr/tbn/tbc outputs
                                    // Priority to tb(c)
                                    String frameRateDoubleString = token.substring(0, token.indexOf("tb"))
                                            .trim();
                                    try {
                                        if (!frameRateDoubleString.equals(getFrameRate())) {// tbc taken into account only if different than tbr
                                            Double frameRateDouble = Double.parseDouble(frameRateDoubleString);
                                            setFrameRate(
                                                    String.format(Locale.ENGLISH, "%.2f", frameRateDouble / 2));
                                        }
                                    } catch (NumberFormatException nfe) {
                                        // Could happen if tbc is "1k" or something like that, no big deal
                                        logger.debug(
                                                "Could not parse frame rate \"" + frameRateDoubleString + "\"");
                                    }

                                } else if ((token.indexOf("tbr") > -1 || token.indexOf("tb(r)") > -1)
                                        && getFrameRate() == null) {
                                    setFrameRate(token.substring(0, token.indexOf("tb")).trim());
                                } else if ((token.indexOf("fps") > -1 || token.indexOf("fps(r)") > -1)
                                        && getFrameRate() == null) { // dvr-ms ?
                                    setFrameRate(token.substring(0, token.indexOf("fps")).trim());
                                } else if (token.indexOf("x") > -1) {
                                    String resolution = token.trim();
                                    if (resolution.indexOf(" [") > -1) {
                                        resolution = resolution.substring(0, resolution.indexOf(" ["));
                                    }
                                    try {
                                        setWidth(Integer
                                                .parseInt(resolution.substring(0, resolution.indexOf("x"))));
                                    } catch (NumberFormatException nfe) {
                                        logger.debug("Could not parse width from \""
                                                + resolution.substring(0, resolution.indexOf("x")) + "\"");
                                    }
                                    try {
                                        setHeight(Integer
                                                .parseInt(resolution.substring(resolution.indexOf("x") + 1)));
                                    } catch (NumberFormatException nfe) {
                                        logger.debug("Could not parse height from \""
                                                + resolution.substring(resolution.indexOf("x") + 1) + "\"");
                                    }
                                }
                            }
                        } else if (line.indexOf("Subtitle:") > -1 && !line.contains("tx3g")) {
                            DLNAMediaSubtitle lang = new DLNAMediaSubtitle();
                            lang.setType((line.contains("dvdsub") && Platform.isWindows() ? SubtitleType.VOBSUB
                                    : SubtitleType.UNKNOWN));
                            int a = line.indexOf("(");
                            int b = line.indexOf("):", a);
                            if (a > -1 && b > a) {
                                lang.setLang(line.substring(a + 1, b));
                            } else {
                                lang.setLang(DLNAMediaLang.UND);
                            }

                            lang.setId(subId++);
                            int FFmpegMetaDataNr = FFmpegMetaData.nextIndex();

                            if (FFmpegMetaDataNr > -1) {
                                line = lines.get(FFmpegMetaDataNr);
                            }

                            if (line.indexOf("Metadata:") > -1) {
                                FFmpegMetaDataNr = FFmpegMetaDataNr + 1;
                                line = lines.get(FFmpegMetaDataNr);

                                while (line.indexOf("      ") == 0) {
                                    if (line.toLowerCase().indexOf("title           :") > -1) {
                                        int aa = line.indexOf(": ");
                                        int bb = line.length();
                                        if (aa > -1 && bb > aa) {
                                            lang.setFlavor(line.substring(aa + 2, bb));
                                            break;
                                        }
                                    } else {
                                        FFmpegMetaDataNr = FFmpegMetaDataNr + 1;
                                        line = lines.get(FFmpegMetaDataNr);
                                    }
                                }
                            }
                            getSubtitleTracksList().add(lang);
                        }
                    }
                }
            }

            if (!thumbOnly && getContainer() != null && inputFile.getFile() != null
                    && getContainer().equals("mpegts") && isH264() && getDurationInSeconds() == 0) {
                // Parse the duration
                try {
                    int length = MpegUtil.getDurationFromMpeg(inputFile.getFile());
                    if (length > 0) {
                        setDuration((double) length);
                    }
                } catch (IOException e) {
                    logger.trace("Error retrieving length: " + e.getMessage());
                }
            }

            if (configuration.isUseMplayerForVideoThumbs() && type == Format.VIDEO && !dvrms) {
                try {
                    getMplayerThumbnail(inputFile);
                    String frameName = "" + inputFile.hashCode();
                    frameName = configuration.getTempFolder() + "/mplayer_thumbs/" + frameName
                            + "00000001/00000001.jpg";
                    frameName = frameName.replace(',', '_');
                    File jpg = new File(frameName);

                    if (jpg.exists()) {
                        InputStream is = new FileInputStream(jpg);
                        int sz = is.available();

                        if (sz > 0) {
                            setThumb(new byte[sz]);
                            is.read(getThumb());
                        }

                        is.close();

                        if (!jpg.delete()) {
                            jpg.deleteOnExit();
                        }

                        // Try and retry
                        if (!jpg.getParentFile().delete() && !jpg.getParentFile().delete()) {
                            logger.debug("Failed to delete \"" + jpg.getParentFile().getAbsolutePath() + "\"");
                        }
                    }
                } catch (IOException e) {
                    logger.debug("Caught exception", e);
                }
            }

            if (type == Format.VIDEO && pw != null && getThumb() == null) {
                InputStream is;
                try {
                    is = pw.getInputStream(0);
                    int sz = is.available();
                    if (sz > 0) {
                        setThumb(new byte[sz]);
                        is.read(getThumb());
                    }
                    is.close();

                    if (sz > 0 && !net.pms.PMS.isHeadless()) {
                        BufferedImage image = ImageIO.read(new ByteArrayInputStream(getThumb()));
                        if (image != null) {
                            Graphics g = image.getGraphics();
                            g.setColor(Color.WHITE);
                            g.setFont(new Font("Arial", Font.PLAIN, 14));
                            int low = 0;
                            if (getWidth() > 0) {
                                if (getWidth() == 1920 || getWidth() == 1440) {
                                    g.drawString("1080p", 0, low += 18);
                                } else if (getWidth() == 1280) {
                                    g.drawString("720p", 0, low += 18);
                                }
                            }
                            ByteArrayOutputStream out = new ByteArrayOutputStream();
                            ImageIO.write(image, "jpeg", out);
                            setThumb(out.toByteArray());
                        }
                    }
                } catch (IOException e) {
                    logger.debug("Error while decoding thumbnail: " + e.getMessage());
                }
            }
        }

        finalize(type, inputFile);
        setMediaparsed(true);
    }
}

From source file:search2go.UIFrame.java

public UIFrame() throws IOException, ParseException {
    topLevels = new TopLevelGTermSet[] { CCs, MFs, BPs };

    this.addWindowListener(new WindowAdapter() {
        @Override//from   w  w w . jav  a  2 s.  co m
        public void windowClosing(WindowEvent et) {
            try {
                if (os.isWindows()) {
                    Runtime.getRuntime().exec("cmd /C TaskKill -IM blastx.exe -F");
                    Runtime.getRuntime().exec("cmd /C TaskKill -IM blastn.exe -F");
                    Runtime.getRuntime().exec("cmd /C TaskKill -IM blastp.exe -F");
                    Runtime.getRuntime().exec("cmd /C TaskKill -IM python.exe -F");
                } else {
                    Runtime.getRuntime().exec("killAll -KILL blastx");
                    Runtime.getRuntime().exec("killAll -KILL blastn");
                    Runtime.getRuntime().exec("killAll -KILL blastp");
                    Runtime.getRuntime().exec("killAll -KILL python");
                }
            } catch (IOException ex) {
                System.out.println("Error closing child processes");
            }
        }
    });

    initComponents();

    txtBlastOutput.getDocument().addDocumentListener(new BufferEnforcer(txtBlastOutput));
    txtFullOutput.getDocument().addDocumentListener(new BufferEnforcer(txtFullOutput));
    txtMapOutput.getDocument().addDocumentListener(new BufferEnforcer(txtMapOutput));

    ((DefaultCaret) txtBlastOutput.getCaret()).setUpdatePolicy(DefaultCaret.ALWAYS_UPDATE);
    ((DefaultCaret) txtMapOutput.getCaret()).setUpdatePolicy(DefaultCaret.ALWAYS_UPDATE);
    ((DefaultCaret) txtFullOutput.getCaret()).setUpdatePolicy(DefaultCaret.ALWAYS_UPDATE);

    webSaveMenu = new JPopupMenu();
    JMenuItem saveWeb = new JMenuItem();
    saveWeb.setText("Save");
    saveWeb.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            webSaveDialogue.showSaveDialog(pnlChartHolder);
            File saveFile = webSaveDialogue.getSelectedFile();
            if (!saveFile.getPath().contains(".png"))
                saveFile = new File(saveFile.getPath() + ".png");
            try {
                BufferedImage webChartImage = new BufferedImage(pnlChartHolder.getWidth(),
                        pnlChartHolder.getHeight(), BufferedImage.TYPE_INT_RGB);
                pnlChartHolder.print(webChartImage.getGraphics());
                ImageIO.write(webChartImage, "png", saveFile);
            } catch (Exception ex) {
                javax.swing.JOptionPane.showMessageDialog(pnlChartHolder,
                        "Error saving chart. Please try again.");
            }
        }

    });
    webSaveMenu.add(saveWeb);
    pnlChartHolder.add(webSaveMenu);
    pnlChartHolder.setLayout(new java.awt.BorderLayout());

    try {
        currentProj = Workspace.open(new Path("Search2GO_Data"));
        chkDoCCs.setState(currentProj.willDoCC());
        chkDoBPs.setState(currentProj.willDoBP());
        chkDoMFs.setState(currentProj.willDoMF());
        txtQuery.setText(currentProj.getQueryPath());
        txtQueryFP.setText(currentProj.getQueryPath());
        txtDatabase.setText(currentProj.getPathToDB());
        txtDatabaseFP.setText(currentProj.getPathToDB());
        txtThreads.setValue(currentProj.getThreadNo());
        txtThreadsFP.setValue(currentProj.getThreadNo());
        cbxNXP.setSelectedIndex(currentProj.getBlastTypeIndex());
        cbxNXPFP.setSelectedIndex(currentProj.getBlastTypeIndex());
        cbxDBID.setSelectedIndex(currentProj.getSelectedDBIndex());
        cbxDBIDFP.setSelectedIndex(currentProj.getSelectedDBIndex());
        txtBitScore.setValue(currentProj.getBitScoreThreshold());
        txtBitScoreFP.setValue(currentProj.getBitScoreThreshold());
        txtBlastE.setValue(currentProj.getEThreshold());
        txtMapE.setValue(currentProj.getEThreshold());
        txtEFP.setValue(currentProj.getEThreshold());
    } catch (FileNotFoundException e) {
        currentProj = Workspace.create(new Path("Search2GO_Data"));
        chkDoCCs.setState(currentProj.willDoCC());
        chkDoBPs.setState(currentProj.willDoBP());
        chkDoMFs.setState(currentProj.willDoMF());
    }
    this.setTitle("Search2GO " + currentProj.getPath().toString());

    GTermTableModel = new DefaultTableModel();
    GTermTableModel.setColumnCount(2);
    GTermTableModel.setColumnIdentifiers(new String[] { "GO ID", "Frequency" });

    ListSelectionModel GTermSelector = tblGOFreq.getSelectionModel();
    GTermSelector.addListSelectionListener(new ListSelectionListener() {
        @Override
        public void valueChanged(ListSelectionEvent e) {
            if (!e.getValueIsAdjusting()) {
                if (tblGOFreq.getSelectedRow() > -1) {
                    DefaultListModel emptyModel = new DefaultListModel();
                    lstQueries.setModel(emptyModel);
                    txtTermInfo.setText("");
                    String selectedID = (String) tblGOFreq.getValueAt(tblGOFreq.getSelectedRow(), 0);
                    JTextArea tempHolderInfo = new JTextArea();
                    JTextArea tempHolderQueries = new JTextArea();

                    if (tblGOFreq.getSelectedRow() != -1) {
                        ResetGTermInfoGetter(tempHolderInfo, tempHolderQueries);
                        gTermInfoGetter.getProcess(0).addParameter("id",
                                selectedID.substring(0, selectedID.indexOf("[")));
                        gTermInfoGetter.getProcess(1).addParameter("id",
                                selectedID.substring(0, selectedID.indexOf("[")));
                        GTerm currentGTerm = gTerms.getGTerm(selectedID.substring(0, selectedID.indexOf("[")));
                        gTermInfoGetter.getProcess(1).addParameter("db", currentGTerm.getTopLevel().getCode());
                        gTermInfoGetter.setTail(new ProcessSequenceEnd() {
                            @Override
                            public void run() {
                                tempHolderInfo.setText("id: " + selectedID + "\n" + tempHolderInfo.getText());
                                txtTermInfo.setText(tempHolderInfo.getText());

                                DefaultListModel queryList = new DefaultListModel();
                                for (String str : tempHolderQueries.getText().split(";")) {
                                    queryList.addElement(str.replaceAll("Query: ", ""));
                                }

                                lstQueries.setModel(queryList);
                                prgIdentification.setIndeterminate(false);
                            }
                        });
                        try {
                            gTermInfoGetter.start();
                            prgIdentification.setIndeterminate(true);
                        } catch (IOException ex) {
                            Logger.getLogger(UIFrame.class.getName()).log(Level.SEVERE, null, ex);
                        }
                    }
                }
            }
        }
    });

    lstQueries.addListSelectionListener(new ListSelectionListener() {
        @Override
        public void valueChanged(ListSelectionEvent e) {
            if (!e.getValueIsAdjusting() && !e.toString().contains("invalid")
                    && lstQueries.getSelectedValue() != null) {
                JTextArea tempHolder = new JTextArea();

                ProcessSequence fetchLocusSequence = new ProcessSequence(new ProcessSequenceEnd() {
                    @Override
                    public void run() {
                        if (txtTermInfo.getText().contains("Score")) {
                            txtTermInfo.setText(
                                    txtTermInfo.getText().substring(0, txtTermInfo.getText().indexOf("Score")));
                        }
                        txtTermInfo.append(tempHolder.getText());
                        prgIdentification.setIndeterminate(false);
                    }
                });
                Path fetchLocusPath = new Path("Processes");
                fetchLocusPath.append("fetchLocus.py");
                Process fetchLocus = new Process(tempHolder);
                fetchLocus.setScriptCommand(fetchLocusPath.toEscString());
                fetchLocus.addParameter("dir", currentProj.getPath().toEscString());
                fetchLocus.addParameter("q",
                        new ParameterString(lstQueries.getSelectedValue().replace("\n", "")).toString());

                String selectedID = (String) tblGOFreq.getValueAt(tblGOFreq.getSelectedRow(), 0);
                GTerm currentGTerm = gTerms.getGTerm(selectedID.substring(0, selectedID.indexOf("[")));
                fetchLocus.addParameter("db", currentGTerm.getTopLevel().getCode());
                fetchLocus.addParameter("id", currentGTerm.getID());
                fetchLocusSequence.addProcess(fetchLocus);

                try {
                    fetchLocusSequence.start();
                    prgIdentification.setIndeterminate(true);
                } catch (IOException ex) {
                    Logger.getLogger(UIFrame.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        }
    });

    DocumentListener filterListener = new DocumentListener() {
        private void anyUpdate() {
            gTerms.getFilter().setFilterString(txtSearchTerms.getText());
            if (!txtMinFreqFilter.getText().equals(""))
                gTerms.getFilter().setMinFreq(Integer.parseInt(txtMinFreqFilter.getText()));
            else
                gTerms.getFilter().setMinFreq(0);
            if (!txtMaxFreqFilter.getText().equals(""))
                gTerms.getFilter().setMaxFreq(Integer.parseInt(txtMaxFreqFilter.getText()));
            else
                gTerms.getFilter().setMaxFreq(-1);
            fillIdentTable(gTerms.stringFilter(), false);
        }

        @Override
        public void insertUpdate(DocumentEvent e) {
            anyUpdate();
        }

        @Override
        public void removeUpdate(DocumentEvent e) {
            anyUpdate();
        }

        @Override
        public void changedUpdate(DocumentEvent e) {
            anyUpdate();
        }
    };
    txtSearchTerms.getDocument().addDocumentListener(filterListener);
    txtMinFreqFilter.getDocument().addDocumentListener(filterListener);
    txtMaxFreqFilter.getDocument().addDocumentListener(filterListener);

    NumberFormat numberMask = NumberFormat.getIntegerInstance();
    numberMask.setGroupingUsed(false);
    NumberFormatter numberMasker = new NumberFormatter(numberMask);
    NumberFormatter numberMaskerAndBlank = new NumberFormatter(numberMask) {
        @Override
        public Object stringToValue(String s) throws ParseException {
            if (s == null || s.length() == 0)
                return null;
            return super.stringToValue(s);
        }
    };
    DefaultFormatterFactory numberMaskFactory = new DefaultFormatterFactory(numberMasker);
    DefaultFormatterFactory numberMaskAndBlankFactory = new DefaultFormatterFactory(numberMaskerAndBlank);

    txtThreads.setFormatterFactory(numberMaskFactory);
    txtThreadsFP.setFormatterFactory(numberMaskFactory);
    txtBitScore.setFormatterFactory(numberMaskAndBlankFactory);
    txtBitScoreFP.setFormatterFactory(numberMaskAndBlankFactory);
    txtMinFreqFilter.setFormatterFactory(numberMaskFactory);
    txtMaxFreqFilter.setFormatterFactory(numberMaskFactory);
    txtBlastE.setFormatterFactory(numberMaskAndBlankFactory);
    txtMapE.setFormatterFactory(numberMaskAndBlankFactory);
    txtEFP.setFormatterFactory(numberMaskAndBlankFactory);

    blastButton = new StopButton(btnBlast);
    mapButton = new StopButton(btnMapIDs);
    identButton = new StopButton(btnGTermIdent);
    fullButton = new StopButton(btnProcessFP);

    if (currentProj.getStage() >= 2)
        identify(false);
}

From source file:edu.harvard.iq.dvn.core.web.servlet.FileDownloadServlet.java

private boolean generateImageThumb(StudyFile file) {

    String fileLocation = file.getFileSystemLocation();
    if (fileLocation == null || fileLocation.trim().equals("")) {
        return false;
    }//from   w w  w. j a v  a 2 s  . c  o m
    String thumbFileLocation = fileLocation + ".thumb";

    // see if the thumb is already generated and saved:

    if (new File(thumbFileLocation).exists()) {
        return true;
    }

    // let's attempt to generate the thumb:

    // the default size of the thumbnail is 64 pixels horizontally.
    // The number 64 was picked arbitrarily; if a different size is 
    // desired, it can be configured via the dvn.image.thumbnail.size 
    // JVM option.

    Long thumbSize = Long.valueOf(64);

    String thumbSizeOption = System.getProperty("dvn.image.thumbnail.size");

    if (thumbSizeOption != null) {
        Long thumbSizeOptionValue = null;
        try {
            thumbSizeOptionValue = new Long(thumbSizeOption);
        } catch (NumberFormatException nfe) {
            // if the supplied option value is invalid/unparseable, we
            // ignore it and fall back to the default value. 
        }
        if (thumbSizeOptionValue != null && thumbSizeOptionValue.longValue() > 0) {
            thumbSize = thumbSizeOptionValue;
        }
    }

    // it is also possible to configure the thumbnail size for a 
    // specific dataverse: 

    VDC vdc = file.getStudy().getOwner();

    if (vdc != null) {
        thumbSizeOption = System.getProperty("dvn.image.thumbnail.size." + vdc.getAlias());

        if (thumbSizeOption != null) {
            Long thumbSizeOptionValue = null;
            try {
                thumbSizeOptionValue = new Long(thumbSizeOption);
            } catch (NumberFormatException nfe) {
                // if the supplied option value is invalid/unparseable, we
                // ignore it and fall back to the default value. 
            }
            if (thumbSizeOptionValue != null && thumbSizeOptionValue.longValue() > 0) {
                thumbSize = thumbSizeOptionValue;
            }
        }
    }

    // This is the default location of the "convert" executable from the
    // ImageMagick package. If it's installed in a different locaiton, 
    // it can be configured via the dvn.image.convert.exec JVM option. 

    String imageMagickConvertExec = "/usr/bin/convert";

    String imageMagickConvertExecOption = System.getProperty("dvn.image.convrt.exec");

    if (imageMagickConvertExecOption != null) {
        if (!imageMagickConvertExecOption.trim().equals("")) {
            imageMagickConvertExec = imageMagickConvertExecOption.trim();
        }
    }

    if (new File(imageMagickConvertExec).exists()) {
        String sizeOption = " -size " + thumbSize + "x" + thumbSize + " ";

        String ImageMagickCommandLine = imageMagickConvertExec + sizeOption + fileLocation + " -resize "
                + thumbSize + " -flatten png:" + thumbFileLocation;
        int exitValue = 1;

        try {
            Runtime runtime = Runtime.getRuntime();
            Process process = runtime.exec(ImageMagickCommandLine);
            exitValue = process.waitFor();
        } catch (Exception e) {
            exitValue = 1;
        }

        if (exitValue == 0) {
            return true;
        }
    }

    // For whatever reason, creating the thumbnail with ImageMagick
    // has failed.
    // Let's try again, this time with Java's standard Image
    // library:

    try {
        BufferedImage fullSizeImage = ImageIO.read(new File(fileLocation));

        if (fullSizeImage == null) {
            return false;
        }

        double scaleFactor = (thumbSize.doubleValue()) / (double) fullSizeImage.getWidth(null);
        int thumbHeight = (int) (fullSizeImage.getHeight(null) * scaleFactor);

        // We are willing to spend a few extra CPU cycles to generate
        // better-looking thumbnails, hence the SCALE_SMOOTH flag. 
        // SCALE_FAST would trade quality for speed. 

        java.awt.Image thumbImage = fullSizeImage.getScaledInstance(thumbSize.intValue(), thumbHeight,
                java.awt.Image.SCALE_SMOOTH);

        ImageWriter writer = null;
        Iterator iter = ImageIO.getImageWritersByFormatName("png");
        if (iter.hasNext()) {
            writer = (ImageWriter) iter.next();
        } else {
            return false;
        }

        BufferedImage lowRes = new BufferedImage(thumbSize.intValue(), thumbHeight, BufferedImage.TYPE_INT_RGB);
        lowRes.getGraphics().drawImage(thumbImage, 0, 0, null);

        ImageOutputStream ios = ImageIO.createImageOutputStream(new File(thumbFileLocation));
        writer.setOutput(ios);

        // finally, save thumbnail image:
        writer.write(lowRes);
        writer.dispose();

        ios.close();
        thumbImage.flush();
        fullSizeImage.flush();
        lowRes.flush();
        return true;
    } catch (Exception e) {
        // something went wrong, returning "false":
        dbgLog.info("ImageIO: caught an exception while trying to generate a thumbnail for " + fileLocation);

        return false;
    }
}

From source file:com.flexoodb.common.FlexUtils.java

static public void createTextBanner(String text, int fontsize, int width, int height, int x, int y,
        String outputfile) throws Exception {
    BufferedImage img = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
    img.createGraphics();//from  ww  w . jav a2 s  .  c  o m
    Graphics2D g = (Graphics2D) img.getGraphics();
    g.setColor(Color.WHITE);
    g.fillRect(0, 0, img.getWidth(), img.getHeight());
    Font font = new Font("Arial", Font.BOLD, fontsize);
    g.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_LCD_HRGB);
    g.setFont(font);
    g.setColor(Color.BLUE.darker());
    g.drawString(text, x, y);
    ImageIO.write(img, "png", new File(outputfile));
}

From source file:pl.edu.icm.visnow.lib.utils.ImageUtilities.java

public static BufferedImage rotateImage(BufferedImage img, double angle, int type, Color fillBgColor) {
    if (img == null) {
        return null;
    }//from   w ww  .j  av a 2  s.  c  o m

    if (angle > 360.0 || angle < -360) {
        angle = angle % 360.0;
    }

    if (angle < 0) {
        angle = 360 + angle;
    }

    if (angle == 0.0 || angle == 360.0) {
        return img;
    }

    //System.out.println("angle="+angle);

    int w = img.getWidth();
    int h = img.getHeight();

    /*
    AffineTransform tr = new AffineTransform();
    tr.rotate(theta,w/2,h/2);
    BufferedImageOp op = new AffineTransformOp(tr, type);
    BufferedImage out = op.filter(img,null);
     */
    /*
    AffineTransform tr = new AffineTransform();
    tr.rotate(theta, w/2.0, h/2.0);
    AffineTransform translationTransform = findTranslation(tr, img);
    tr.preConcatenate(translationTransform);
    BufferedImageOp op = new AffineTransformOp(tr, type);
            
    BufferedImage out = op.filter(img,null);
     */
    BufferedImage out = null;
    if (angle == 90.0 || angle == 180.0 || angle == 270.0) {
        switch ((int) angle) {
        case 90:
            out = new BufferedImage(h, w, img.getType());
            for (int x = 0; x < w; x++) {
                for (int y = 0; y < h; y++) {
                    out.setRGB(h - y - 1, x, img.getRGB(x, y));
                }
            }
            break;
        case 180:
            out = new BufferedImage(w, h, img.getType());
            for (int x = 0; x < w; x++) {
                for (int y = 0; y < h; y++) {
                    out.setRGB(w - x - 1, h - y - 1, img.getRGB(x, y));
                }
            }
            break;
        case 270:
            out = new BufferedImage(h, w, img.getType());
            for (int x = 0; x < w; x++) {
                for (int y = 0; y < h; y++) {
                    out.setRGB(y, w - x - 1, img.getRGB(x, y));
                }
            }
            break;
        }
    } else {
        double theta = angle * Math.PI / 180.0;
        int neww = w, newh = h;
        double dx = 0.0, dy = 0.0;
        double s = Math.sin(theta);
        double c = Math.cos(theta);
        if (angle > 0.0 && angle < 90.0) {
            neww = (int) Math.round(((double) w) * c + ((double) h) * s);
            newh = (int) Math.round(((double) w) * s + ((double) h) * c);
            dx = ((double) h) * s;
            dy = 0.0;
        } else if (angle > 90.0 && angle < 180.0) {
            neww = (int) Math.round(-((double) w) * c + ((double) h) * s);
            newh = (int) Math.round(((double) w) * s - ((double) h) * c);
            dx = -((double) w) * c + ((double) h) * s;
            dy = -((double) h) * c;
        } else if (angle > 180.0 && angle < 270.0) {
            neww = (int) Math.round(-((double) w) * c - ((double) h) * s);
            newh = (int) Math.round(-((double) w) * s - ((double) h) * c);
            dx = -((double) w) * c;
            dy = -((double) w) * s - ((double) h) * c;
        } else if (angle > 270.0 && angle < 360.0) {
            neww = (int) Math.round(((double) w) * c - ((double) h) * s);
            newh = (int) Math.round(-((double) w) * s + ((double) h) * c);
            dx = 0.0;
            dy = -((double) w) * s;
        }

        AffineTransform tr = new AffineTransform();
        tr.translate(dx, dy);
        tr.rotate(theta);
        BufferedImageOp op = new AffineTransformOp(tr, type);
        out = new BufferedImage(neww, newh, img.getType());
        Graphics2D g2d = (Graphics2D) out.getGraphics();
        Rectangle clear = new Rectangle(0, 0, out.getWidth(), out.getHeight());
        g2d.setPaint(fillBgColor);
        g2d.fill(clear);
        op.filter(img, out);
    }
    return out;
}

From source file:com.flexoodb.common.FlexUtils.java

static public BufferedImage createCaptcha(String text, Color background, Color fontcolor, int fontsize,
        int width, int height, int x, int y) throws Exception {
    BufferedImage img = new BufferedImage(width + 10, height, BufferedImage.TYPE_INT_RGB);
    img.createGraphics();/*w w w.java2s.  c  om*/
    Graphics2D g = (Graphics2D) img.getGraphics();
    g.setColor(background);
    g.fillRect(0, 0, img.getWidth(), img.getHeight());
    Font font = new Font("Monospaced", Font.BOLD + Font.ITALIC, fontsize);

    g.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_LCD_HRGB);
    g.setFont(font);
    g.setColor(fontcolor);

    char[] c = text.toCharArray();

    java.util.Random random = new java.util.Random();

    for (int i = 0; i < c.length; i++) {
        int j = random.nextInt(9);
        if (j > 5) {
            j = j - 5;
        } else {
            j = -1 * (j - 2);
        }

        char[] c1 = new char[1];
        c1[0] = c[i];
        g.drawChars(c1, 0, 1, x + (i * 16), y + j);
    }

    for (int i = -10; i < 20; i++) {
        int j = random.nextInt(8);
        g.drawOval((i + j) - 20, ((i * 8) - (j > 3 ? 4 : -4)), width + 20, height);
    }
    //ImageIO.write(img,"png",new File(outputfile));
    return img;

}

From source file:org.openmicroscopy.shoola.agents.imviewer.view.ImViewerModel.java

/**
 * Clears the images hosted by the tile if not <code>null</code>.
 * //from   ww  w .j a  v a2 s .  c  o m
 * @param toClear The collection to handle.
 */
void clearTileImages(Collection<Tile> toClear) {
    if (toClear == null || toClear.size() == 0)
        return;
    Iterator<Tile> i = toClear.iterator();
    Tile tile;
    Object image;
    BufferedImage bi;
    TextureData data;
    while (i.hasNext()) {
        tile = i.next();
        image = tile.getImage();
        if (image != null) {
            if (image instanceof BufferedImage) {
                bi = (BufferedImage) image;
                bi.getGraphics().dispose();
                bi.flush();
                tile.setImage(null);
            } else {
                data = (TextureData) image;
                data.flush();
                tile.setImage(null);
            }
        }
    }
}

From source file:org.pentaho.reporting.engine.classic.core.modules.output.pageable.pdf.internal.PdfGraphics2D.java

private void setPaint(final boolean invert, final double xoffset, final double yoffset, final boolean fill) {
    if (paint instanceof Color) {
        final Color color = (Color) paint;
        final int alpha = color.getAlpha();
        if (fill) {
            if (alpha != currentFillGState) {
                currentFillGState = alpha;
                PdfGState gs = fillGState[alpha];
                if (gs == null) {
                    gs = new PdfGState();
                    gs.setFillOpacity(alpha / 255.00f);
                    fillGState[alpha] = gs;
                }/*from  w  ww .  j ava2s .c  o m*/
                cb.setGState(gs);
            }
            cb.setColorFill(color);
        } else {
            if (alpha != currentStrokeGState) {
                currentStrokeGState = alpha;
                PdfGState gs = strokeGState[alpha];
                if (gs == null) {
                    gs = new PdfGState();
                    gs.setStrokeOpacity(alpha / 255.0f);
                    strokeGState[alpha] = gs;
                }
                cb.setGState(gs);
            }
            cb.setColorStroke(color);
        }
    } else if (paint instanceof GradientPaint) {
        final GradientPaint gp = (GradientPaint) paint;
        final Point2D p1 = gp.getPoint1();
        transform.transform(p1, p1);
        final Point2D p2 = gp.getPoint2();
        transform.transform(p2, p2);
        final Color c1 = gp.getColor1();
        final Color c2 = gp.getColor2();
        final PdfShading shading = PdfShading.simpleAxial(cb.getPdfWriter(), (float) p1.getX(),
                normalizeY((float) p1.getY()), (float) p2.getX(), normalizeY((float) p2.getY()), c1, c2);
        final PdfShadingPattern pat = new PdfShadingPattern(shading);
        if (fill) {
            cb.setShadingFill(pat);
        } else {
            cb.setShadingStroke(pat);
        }
    } else if (paint instanceof TexturePaint) {
        try {
            final TexturePaint tp = (TexturePaint) paint;
            final BufferedImage img = tp.getImage();
            final Rectangle2D rect = tp.getAnchorRect();
            final com.lowagie.text.Image image = com.lowagie.text.Image.getInstance(img, null);
            final PdfPatternPainter pattern = cb.createPattern(image.getWidth(), image.getHeight());
            final AffineTransform inverse = this.normalizeMatrix();
            inverse.translate(rect.getX(), rect.getY());
            inverse.scale(rect.getWidth() / image.getWidth(), -rect.getHeight() / image.getHeight());
            final double[] mx = new double[6];
            inverse.getMatrix(mx);
            pattern.setPatternMatrix((float) mx[0], (float) mx[1], (float) mx[2], (float) mx[3], (float) mx[4],
                    (float) mx[5]);
            image.setAbsolutePosition(0, 0);
            pattern.addImage(image);
            if (fill) {
                cb.setPatternFill(pattern);
            } else {
                cb.setPatternStroke(pattern);
            }

        } catch (Exception ex) {
            if (fill) {
                cb.setColorFill(Color.gray);
            } else {
                cb.setColorStroke(Color.gray);
            }
        }
    } else {
        try {
            int type = BufferedImage.TYPE_4BYTE_ABGR;
            if (paint.getTransparency() == Transparency.OPAQUE) {
                type = BufferedImage.TYPE_3BYTE_BGR;
            }
            final BufferedImage img = new BufferedImage((int) width, (int) height, type);
            final Graphics2D g = (Graphics2D) img.getGraphics();
            g.transform(transform);
            final AffineTransform inv = transform.createInverse();
            Shape fillRect = new Rectangle2D.Double(0, 0, img.getWidth(), img.getHeight());
            fillRect = inv.createTransformedShape(fillRect);
            g.setPaint(paint);
            g.fill(fillRect);
            if (invert) {
                final AffineTransform tx = new AffineTransform();
                tx.scale(1, -1);
                tx.translate(-xoffset, -yoffset);
                g.drawImage(img, tx, null);
            }
            g.dispose();
            // g = null;
            final com.lowagie.text.Image image = com.lowagie.text.Image.getInstance(img, null);
            final PdfPatternPainter pattern = cb.createPattern(width, height);
            image.setAbsolutePosition(0, 0);
            pattern.addImage(image);
            if (fill) {
                cb.setPatternFill(pattern);
            } else {
                cb.setPatternStroke(pattern);
            }
        } catch (Exception ex) {
            if (fill) {
                cb.setColorFill(Color.gray);
            } else {
                cb.setColorStroke(Color.gray);
            }
        }
    }
}