Example usage for java.awt Image SCALE_AREA_AVERAGING

List of usage examples for java.awt Image SCALE_AREA_AVERAGING

Introduction

In this page you can find the example usage for java.awt Image SCALE_AREA_AVERAGING.

Prototype

int SCALE_AREA_AVERAGING

To view the source code for java.awt Image SCALE_AREA_AVERAGING.

Click Source Link

Document

Use the Area Averaging image scaling algorithm.

Usage

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

/**
 * ?????????/*  w w  w .j a  v  a 2 s. co m*/
 * 
 * @param imgfile
 * @param dim
 * @return
 */
public static BufferedImage shrinkImage(BufferedImage imgfile, int width, int height) {

    int iwidth = imgfile.getWidth();
    int iheight = imgfile.getHeight();

    double ratio = Math.min((double) width / (double) iwidth, (double) height / (double) iheight);
    int shrinkedWidth = (int) (iwidth * ratio);
    int shrinkedHeight = (int) (iheight * ratio);

    // ??
    Image targetImage = imgfile.getScaledInstance(shrinkedWidth, shrinkedHeight, Image.SCALE_AREA_AVERAGING);
    BufferedImage tmpImage = new BufferedImage(targetImage.getWidth(null), targetImage.getHeight(null),
            BufferedImage.TYPE_3BYTE_BGR);
    Graphics2D g = tmpImage.createGraphics();
    g.setColor(Color.WHITE);
    g.fillRect(0, 0, shrinkedWidth, shrinkedHeight);
    g.drawImage(targetImage, 0, 0, null);

    return tmpImage;
}

From source file:info.magnolia.cms.taglibs.util.TextToImageTag.java

/**
 * Create an image file that is a scaled version of the original image
 * @param the original BufferedImage// w ww  . j a v  a  2 s .c  om
 * @param the scale factor
 * @return the new BufferedImage
 */
private BufferedImage scaleImage(BufferedImage oriImgBuff, double scaleFactor) {

    // get the dimesnions of the original image
    int oriWidth = oriImgBuff.getWidth();
    int oriHeight = oriImgBuff.getHeight();
    // get the width and height of the new image
    int newWidth = new Double(oriWidth * scaleFactor).intValue();
    int newHeight = new Double(oriHeight * scaleFactor).intValue();
    // create the thumbnail as a buffered image
    Image newImg = oriImgBuff.getScaledInstance(newWidth, newHeight, Image.SCALE_AREA_AVERAGING);
    BufferedImage newImgBuff = new BufferedImage(newImg.getWidth(null), newImg.getHeight(null),
            BufferedImage.TYPE_INT_RGB);
    Graphics2D g = newImgBuff.createGraphics();
    g.drawImage(newImg, 0, 0, null);
    g.dispose();
    // return the newImgBuff
    return newImgBuff;
}

From source file:MyFormApp.java

void pdfToimage(File filename) throws FileNotFoundException, IOException { //?pdf ?

    // TODO Auto-generated method stub
    File pdfFile = new File(filename.toString()); // pdf
    RandomAccessFile raf = new RandomAccessFile(pdfFile, "r");
    FileChannel channel = raf.getChannel();
    ByteBuffer buf = channel.map(FileChannel.MapMode.READ_ONLY, 0, channel.size());
    PDFFile pdf = new PDFFile(buf);

    int i = 0;//www  . j  ava  2 s .co  m
    String fileNameWithOutExt = FilenameUtils.removeExtension(filename.getName());

    Rectangle rect = new Rectangle(0, 0, (int) pdf.getPage(i).getBBox().getWidth(), //
            (int) pdf.getPage(i).getBBox().getHeight());
    BufferedImage bufferedImage = new BufferedImage(100, 100, BufferedImage.TYPE_INT_RGB);

    Image image = pdf.getPage(i).getImage(rect.width, rect.height, // width & height
            rect, // clip rect
            null, // null for the ImageObserver
            true, // fill background with white
            true // block until drawing is done
    );
    Graphics2D bufImageGraphics = bufferedImage.createGraphics();
    bufImageGraphics.drawImage(image.getScaledInstance(100, 100, Image.SCALE_AREA_AVERAGING), 0, 0, null);

    ImageIO.write(bufferedImage, "PNG", new File(PATH + fileNameWithOutExt + ".png")); //? 
}

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

/**
 * ???/*from  www .  ja  va2 s.  c o  m*/
 * 
 * @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: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);
    }/*  ww  w.ja v  a  2 s  .  c  om*/

    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:Interfaz.adminZone.java

private void cbEmpActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cbEmpActionPerformed
    ArrayList<String> arr = con.search(6,
            "E.Nombre, C.Nombre Cargo, E.Telefono, COUNT(Empleado), " + "SUM(ValorTotal), E.Documento", "Venta",
            "INNER JOIN Empleado E ON E.Documento = Venta.Empleado "
                    + "INNER JOIN Cargo C ON E.Cargo = C.IdCargo " + "GROUP BY Empleado HAVING E.Nombre =" + "'"
                    + this.cbEmp.getSelectedItem().toString() + "'");
    this.txtCargo.setText(arr.get(1));
    this.txtTelefono.setText(arr.get(2));
    this.txtCan.setText(arr.get(3));
    this.txtTotal.setText(arr.get(4));

    Toolkit tk = Toolkit.getDefaultToolkit();
    String ruta = "./_data/" + arr.get(5) + ".jpg";
    Image imagen = tk.createImage(ruta);
    fotoEmp.setIcon(new ImageIcon(
            imagen.getScaledInstance(fotoEmp.getWidth(), fotoEmp.getHeight(), Image.SCALE_AREA_AVERAGING)));

}

From source file:net.yacy.cora.util.Html2Image.java

/**
 * convert a pdf (first page) to an image. proper values are i.e. width = 1024, height = 1024, density = 300, quality = 75
 * using internal pdf library or external command line tool on linux or mac
 * @param pdf input pdf file/*w w w . j  a  va2  s. c o  m*/
 * @param image output jpg file
 * @param width
 * @param height
 * @param density (dpi)
 * @param quality
 * @return
 */
public static boolean pdf2image(File pdf, File image, int width, int height, int density, int quality) {
    final File convert = convertMac1.exists() ? convertMac1
            : convertMac2.exists() ? convertMac2 : convertDebian;

    // convert pdf to jpg using internal pdfbox capability
    if (OS.isWindows || !convert.exists()) {
        try {
            PDDocument pdoc = PDDocument.load(pdf);
            BufferedImage bi = new PDFRenderer(pdoc).renderImageWithDPI(0, density, ImageType.RGB);

            return ImageIO.write(bi, "jpg", image);

        } catch (IOException ex) {
        }
    }

    // convert on mac or linux using external command line utility
    try {
        // i.e. convert -density 300 -trim yacy.pdf[0] -trim -resize 1024x -crop x1024+0+0 -quality 75% yacy-convert-300.jpg
        // note: both -trim are necessary, otherwise it is trimmed only on one side. The [0] selects the first page of the pdf
        String command = convert.getAbsolutePath() + " -density " + density + " -trim " + pdf.getAbsolutePath()
                + "[0] -trim -resize " + width + "x -crop x" + height + "+0+0 -quality " + quality + "% "
                + image.getAbsolutePath();
        List<String> message = OS.execSynchronous(command);
        if (image.exists())
            return true;
        ConcurrentLog.warn("Html2Image", "failed to create image with command: " + command);
        for (String m : message)
            ConcurrentLog.warn("Html2Image", ">> " + m);

        // another try for mac: use Image Events using AppleScript in osacript commands...
        // the following command overwrites a pdf with an png, so we must make a copy first
        if (!OS.isMacArchitecture)
            return false;
        File pngFile = new File(pdf.getAbsolutePath() + ".tmp.pdf");
        org.apache.commons.io.FileUtils.copyFile(pdf, pngFile);
        String[] commandx = { "osascript", "-e", "set ImgFile to \"" + pngFile.getAbsolutePath() + "\"", "-e",
                "tell application \"Image Events\"", "-e", "set Img to open file ImgFile", "-e",
                "save Img as PNG", "-e", "end tell" };
        //ConcurrentLog.warn("Html2Image", "failed to create image with command: " + commandx);
        message = OS.execSynchronous(commandx);
        for (String m : message)
            ConcurrentLog.warn("Html2Image", ">> " + m);
        // now we must read and convert this file to a jpg with the target size 1024x1024
        try {
            File newPngFile = new File(pngFile.getAbsolutePath() + ".png");
            pngFile.renameTo(newPngFile);
            Image img = ImageParser.parse(pngFile.getAbsolutePath(), FileUtils.read(newPngFile));
            final Image scaled = img.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) {
            }
            // finally write the image
            final BufferedImage bi = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
            bi.createGraphics().drawImage(scaled, 0, 0, width, height, null);
            ImageIO.write(bi, "jpg", image);
            newPngFile.delete();
            return image.exists();
        } catch (IOException e) {
            ConcurrentLog.logException(e);
            return false;
        }
    } catch (IOException e) {
        e.printStackTrace();
        return false;
    }
}

From source file:org.jtrfp.trcl.core.ResourceManager.java

private BufferedImage[] getSpecialRAWImage(String name, Color[] palette, int upscalePowerOfTwo)
        throws IllegalAccessException, FileLoadException, IOException {
    RAWFile dat = getRAW(name);/*from  w  w  w .j a  v  a2 s  . c o m*/
    dat.setPalette(palette);
    BufferedImage[] segs = dat.asSegments(upscalePowerOfTwo);
    for (BufferedImage seg : segs) {
        Graphics g = seg.getGraphics();
        BufferedImage scaled = new BufferedImage(seg.getColorModel(), seg.copyData(null),
                seg.isAlphaPremultiplied(), null);
        g.drawImage(
                scaled.getScaledInstance(seg.getWidth() - 2, seg.getHeight() - 2, Image.SCALE_AREA_AVERAGING),
                1, 1, seg.getWidth() - 2, seg.getHeight() - 2, null);
        g.dispose();
    }
    return segs;
}

From source file:org.pentaho.ui.xul.swing.tags.SwingImage.java

@Override
public void layout() {
    this.panel.removeAll();

    if (ico == null || !visible) {
        return;//  w ww.  ja v  a  2s  .  co  m
    }

    // If scaling in place resize ImageIcon
    if (getHeight() > 0 && getWidth() > 0) {
        ico = new ImageIcon(
                ico.getImage().getScaledInstance(getWidth(), getHeight(), Image.SCALE_AREA_AVERAGING));
    }
    lbl = new JLabel(ico);
    lbl.setOpaque(false);

    this.panel.add(lbl, BorderLayout.CENTER);

    // Set panel to sizing
    if (getHeight() > 0 && getWidth() > 0) {
        this.panel.setMinimumSize(new Dimension(this.getWidth(), this.getHeight()));
    }

    panel.revalidate();
}

From source file:se.unlogic.hierarchy.foregroundmodules.imagegallery.GalleryModule.java

private void checkSettings(MutableSettingHandler mutableSettingHandler) {

    Integer thumbQuality = mutableSettingHandler.getInt("thumbQuality");

    if (thumbQuality != null && (thumbQuality == Image.SCALE_AREA_AVERAGING || thumbQuality == Image.SCALE_FAST
            || thumbQuality == Image.SCALE_REPLICATE || thumbQuality == Image.SCALE_SMOOTH)) {
        this.thumbQuality = thumbQuality;
    } else if (thumbQuality != null) {
        log.warn("Illegal thumbQuality setting value detected, " + thumbQuality + " in module "
                + this.moduleDescriptor);
    }/*from w  w w .  j a  v  a2s.  co  m*/
}