EffectUtils.java 17.6 KB
Newer Older
P
peterz 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426
/*
 * Copyright 2005-2006 Sun Microsystems, Inc.  All Rights Reserved.
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * This code is free software; you can redistribute it and/or modify it
 * under the terms of the GNU General Public License version 2 only, as
 * published by the Free Software Foundation.  Sun designates this
 * particular file as subject to the "Classpath" exception as provided
 * by Sun in the LICENSE file that accompanied this code.
 *
 * This code is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
 * version 2 for more details (a copy is included in the LICENSE file that
 * accompanied this code).
 *
 * You should have received a copy of the GNU General Public License version
 * 2 along with this work; if not, write to the Free Software Foundation,
 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
 *
 * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
 * CA 95054 USA or visit www.sun.com if you need additional information or
 * have any questions.
 */
package javax.swing.plaf.nimbus;

import java.awt.AlphaComposite;
import java.awt.Graphics2D;
import java.awt.Transparency;
import java.awt.GraphicsConfiguration;
import java.awt.GraphicsEnvironment;
import java.awt.image.BufferedImage;
import java.awt.image.Raster;
import java.awt.image.WritableRaster;
import java.awt.image.ColorModel;

/**
 * EffectUtils
 *
 * @author Created by Jasper Potts (Jun 18, 2007)
 */
class EffectUtils {

    /**
     * Clear a transparent image to 100% transparent
     *
     * @param img The image to clear
     */
    static void clearImage(BufferedImage img) {
        Graphics2D g2 = img.createGraphics();
        g2.setComposite(AlphaComposite.Clear);
        g2.fillRect(0, 0, img.getWidth(), img.getHeight());
        g2.dispose();
    }

    // =================================================================================================================
    // Blur

    /**
     * Apply Gaussian Blur to Image
     *
     * @param src    The image tp
     * @param dst    The destination image to draw blured src image into, null if you want a new one created
     * @param radius The blur kernel radius
     * @return The blured image
     */
    static BufferedImage gaussianBlur(BufferedImage src, BufferedImage dst, int radius) {
        int width = src.getWidth();
        int height = src.getHeight();
        if (dst == null || dst.getWidth() != width || dst.getHeight() != height || src.getType() != dst.getType()) {
            dst = createColorModelCompatibleImage(src);
        }
        float[] kernel = createGaussianKernel(radius);
        if (src.getType() == BufferedImage.TYPE_INT_ARGB) {
            int[] srcPixels = new int[width * height];
            int[] dstPixels = new int[width * height];
            getPixels(src, 0, 0, width, height, srcPixels);
            // horizontal pass
            blur(srcPixels, dstPixels, width, height, kernel, radius);
            // vertical pass
            //noinspection SuspiciousNameCombination
            blur(dstPixels, srcPixels, height, width, kernel, radius);
            // the result is now stored in srcPixels due to the 2nd pass
            setPixels(dst, 0, 0, width, height, srcPixels);
        } else if (src.getType() == BufferedImage.TYPE_BYTE_GRAY) {
            byte[] srcPixels = new byte[width * height];
            byte[] dstPixels = new byte[width * height];
            getPixels(src, 0, 0, width, height, srcPixels);
            // horizontal pass
            blur(srcPixels, dstPixels, width, height, kernel, radius);
            // vertical pass
            //noinspection SuspiciousNameCombination
            blur(dstPixels, srcPixels, height, width, kernel, radius);
            // the result is now stored in srcPixels due to the 2nd pass
            setPixels(dst, 0, 0, width, height, srcPixels);
        } else {
            throw new IllegalArgumentException("EffectUtils.gaussianBlur() src image is not a supported type, type=[" +
                    src.getType() + "]");
        }
        return dst;
    }

    /**
     * <p>Blurs the source pixels into the destination pixels. The force of the blur is specified by the radius which
     * must be greater than 0.</p> <p>The source and destination pixels arrays are expected to be in the INT_ARGB
     * format.</p> <p>After this method is executed, dstPixels contains a transposed and filtered copy of
     * srcPixels.</p>
     *
     * @param srcPixels the source pixels
     * @param dstPixels the destination pixels
     * @param width     the width of the source picture
     * @param height    the height of the source picture
     * @param kernel    the kernel of the blur effect
     * @param radius    the radius of the blur effect
     */
    private static void blur(int[] srcPixels, int[] dstPixels,
                             int width, int height,
                             float[] kernel, int radius) {
        float a;
        float r;
        float g;
        float b;

        int ca;
        int cr;
        int cg;
        int cb;

        for (int y = 0; y < height; y++) {
            int index = y;
            int offset = y * width;

            for (int x = 0; x < width; x++) {
                a = r = g = b = 0.0f;

                for (int i = -radius; i <= radius; i++) {
                    int subOffset = x + i;
                    if (subOffset < 0 || subOffset >= width) {
                        subOffset = (x + width) % width;
                    }

                    int pixel = srcPixels[offset + subOffset];
                    float blurFactor = kernel[radius + i];

                    a += blurFactor * ((pixel >> 24) & 0xFF);
                    r += blurFactor * ((pixel >> 16) & 0xFF);
                    g += blurFactor * ((pixel >> 8) & 0xFF);
                    b += blurFactor * ((pixel) & 0xFF);
                }

                ca = (int) (a + 0.5f);
                cr = (int) (r + 0.5f);
                cg = (int) (g + 0.5f);
                cb = (int) (b + 0.5f);

                dstPixels[index] = ((ca > 255 ? 255 : ca) << 24) |
                        ((cr > 255 ? 255 : cr) << 16) |
                        ((cg > 255 ? 255 : cg) << 8) |
                        (cb > 255 ? 255 : cb);
                index += height;
            }
        }
    }

    /**
     * <p>Blurs the source pixels into the destination pixels. The force of the blur is specified by the radius which
     * must be greater than 0.</p> <p>The source and destination pixels arrays are expected to be in the BYTE_GREY
     * format.</p> <p>After this method is executed, dstPixels contains a transposed and filtered copy of
     * srcPixels.</p>
     *
     * @param srcPixels the source pixels
     * @param dstPixels the destination pixels
     * @param width     the width of the source picture
     * @param height    the height of the source picture
     * @param kernel    the kernel of the blur effect
     * @param radius    the radius of the blur effect
     */
    static void blur(byte[] srcPixels, byte[] dstPixels,
                            int width, int height,
                            float[] kernel, int radius) {
        float p;
        int cp;
        for (int y = 0; y < height; y++) {
            int index = y;
            int offset = y * width;
            for (int x = 0; x < width; x++) {
                p = 0.0f;
                for (int i = -radius; i <= radius; i++) {
                    int subOffset = x + i;
//                    if (subOffset < 0) subOffset = 0;
//                    if (subOffset >= width) subOffset = width-1;
                    if (subOffset < 0 || subOffset >= width) {
                        subOffset = (x + width) % width;
                    }
                    int pixel = srcPixels[offset + subOffset] & 0xFF;
                    float blurFactor = kernel[radius + i];
                    p += blurFactor * pixel;
                }
                cp = (int) (p + 0.5f);
                dstPixels[index] = (byte) (cp > 255 ? 255 : cp);
                index += height;
            }
        }
    }

    static float[] createGaussianKernel(int radius) {
        if (radius < 1) {
            throw new IllegalArgumentException("Radius must be >= 1");
        }

        float[] data = new float[radius * 2 + 1];

        float sigma = radius / 3.0f;
        float twoSigmaSquare = 2.0f * sigma * sigma;
        float sigmaRoot = (float) Math.sqrt(twoSigmaSquare * Math.PI);
        float total = 0.0f;

        for (int i = -radius; i <= radius; i++) {
            float distance = i * i;
            int index = i + radius;
            data[index] = (float) Math.exp(-distance / twoSigmaSquare) / sigmaRoot;
            total += data[index];
        }

        for (int i = 0; i < data.length; i++) {
            data[i] /= total;
        }

        return data;
    }

    // =================================================================================================================
    // Get/Set Pixels helper methods

    /**
     * <p>Returns an array of pixels, stored as integers, from a <code>BufferedImage</code>. The pixels are grabbed from
     * a rectangular area defined by a location and two dimensions. Calling this method on an image of type different
     * from <code>BufferedImage.TYPE_INT_ARGB</code> and <code>BufferedImage.TYPE_INT_RGB</code> will unmanage the
     * image.</p>
     *
     * @param img    the source image
     * @param x      the x location at which to start grabbing pixels
     * @param y      the y location at which to start grabbing pixels
     * @param w      the width of the rectangle of pixels to grab
     * @param h      the height of the rectangle of pixels to grab
     * @param pixels a pre-allocated array of pixels of size w*h; can be null
     * @return <code>pixels</code> if non-null, a new array of integers otherwise
     * @throws IllegalArgumentException is <code>pixels</code> is non-null and of length &lt; w*h
     */
    static byte[] getPixels(BufferedImage img,
                                   int x, int y, int w, int h, byte[] pixels) {
        if (w == 0 || h == 0) {
            return new byte[0];
        }

        if (pixels == null) {
            pixels = new byte[w * h];
        } else if (pixels.length < w * h) {
            throw new IllegalArgumentException("pixels array must have a length >= w*h");
        }

        int imageType = img.getType();
        if (imageType == BufferedImage.TYPE_BYTE_GRAY) {
            Raster raster = img.getRaster();
            return (byte[]) raster.getDataElements(x, y, w, h, pixels);
        } else {
            throw new IllegalArgumentException("Only type BYTE_GRAY is supported");
        }
    }

    /**
     * <p>Writes a rectangular area of pixels in the destination <code>BufferedImage</code>. Calling this method on an
     * image of type different from <code>BufferedImage.TYPE_INT_ARGB</code> and <code>BufferedImage.TYPE_INT_RGB</code>
     * will unmanage the image.</p>
     *
     * @param img    the destination image
     * @param x      the x location at which to start storing pixels
     * @param y      the y location at which to start storing pixels
     * @param w      the width of the rectangle of pixels to store
     * @param h      the height of the rectangle of pixels to store
     * @param pixels an array of pixels, stored as integers
     * @throws IllegalArgumentException is <code>pixels</code> is non-null and of length &lt; w*h
     */
    static void setPixels(BufferedImage img,
                                 int x, int y, int w, int h, byte[] pixels) {
        if (pixels == null || w == 0 || h == 0) {
            return;
        } else if (pixels.length < w * h) {
            throw new IllegalArgumentException("pixels array must have a length >= w*h");
        }
        int imageType = img.getType();
        if (imageType == BufferedImage.TYPE_BYTE_GRAY) {
            WritableRaster raster = img.getRaster();
            raster.setDataElements(x, y, w, h, pixels);
        } else {
            throw new IllegalArgumentException("Only type BYTE_GRAY is supported");
        }
    }

    /**
     * <p>Returns an array of pixels, stored as integers, from a
     * <code>BufferedImage</code>. The pixels are grabbed from a rectangular
     * area defined by a location and two dimensions. Calling this method on
     * an image of type different from <code>BufferedImage.TYPE_INT_ARGB</code>
     * and <code>BufferedImage.TYPE_INT_RGB</code> will unmanage the image.</p>
     *
     * @param img the source image
     * @param x the x location at which to start grabbing pixels
     * @param y the y location at which to start grabbing pixels
     * @param w the width of the rectangle of pixels to grab
     * @param h the height of the rectangle of pixels to grab
     * @param pixels a pre-allocated array of pixels of size w*h; can be null
     * @return <code>pixels</code> if non-null, a new array of integers
     *   otherwise
     * @throws IllegalArgumentException is <code>pixels</code> is non-null and
     *   of length &lt; w*h
     */
    public static int[] getPixels(BufferedImage img,
                                  int x, int y, int w, int h, int[] pixels) {
        if (w == 0 || h == 0) {
            return new int[0];
        }

        if (pixels == null) {
            pixels = new int[w * h];
        } else if (pixels.length < w * h) {
            throw new IllegalArgumentException("pixels array must have a length" +
                                               " >= w*h");
        }

        int imageType = img.getType();
        if (imageType == BufferedImage.TYPE_INT_ARGB ||
            imageType == BufferedImage.TYPE_INT_RGB) {
            Raster raster = img.getRaster();
            return (int[]) raster.getDataElements(x, y, w, h, pixels);
        }

        // Unmanages the image
        return img.getRGB(x, y, w, h, pixels, 0, w);
    }

    /**
     * <p>Writes a rectangular area of pixels in the destination
     * <code>BufferedImage</code>. Calling this method on
     * an image of type different from <code>BufferedImage.TYPE_INT_ARGB</code>
     * and <code>BufferedImage.TYPE_INT_RGB</code> will unmanage the image.</p>
     *
     * @param img the destination image
     * @param x the x location at which to start storing pixels
     * @param y the y location at which to start storing pixels
     * @param w the width of the rectangle of pixels to store
     * @param h the height of the rectangle of pixels to store
     * @param pixels an array of pixels, stored as integers
     * @throws IllegalArgumentException is <code>pixels</code> is non-null and
     *   of length &lt; w*h
     */
    public static void setPixels(BufferedImage img,
                                 int x, int y, int w, int h, int[] pixels) {
        if (pixels == null || w == 0 || h == 0) {
            return;
        } else if (pixels.length < w * h) {
            throw new IllegalArgumentException("pixels array must have a length" +
                                               " >= w*h");
        }

        int imageType = img.getType();
        if (imageType == BufferedImage.TYPE_INT_ARGB ||
            imageType == BufferedImage.TYPE_INT_RGB) {
            WritableRaster raster = img.getRaster();
            raster.setDataElements(x, y, w, h, pixels);
        } else {
            // Unmanages the image
            img.setRGB(x, y, w, h, pixels, 0, w);
        }
    }

    /**
     * <p>Returns a new <code>BufferedImage</code> using the same color model
     * as the image passed as a parameter. The returned image is only compatible
     * with the image passed as a parameter. This does not mean the returned
     * image is compatible with the hardware.</p>
     *
     * @param image the reference image from which the color model of the new
     *   image is obtained
     * @return a new <code>BufferedImage</code>, compatible with the color model
     *   of <code>image</code>
     */
    public static BufferedImage createColorModelCompatibleImage(BufferedImage image) {
        ColorModel cm = image.getColorModel();
        return new BufferedImage(cm,
            cm.createCompatibleWritableRaster(image.getWidth(),
                                              image.getHeight()),
            cm.isAlphaPremultiplied(), null);
    }

    /**
     * <p>Returns a new translucent compatible image of the specified width and
     * height. That is, the returned <code>BufferedImage</code> is compatible with
     * the graphics hardware. If the method is called in a headless
     * environment, then the returned BufferedImage will be compatible with
     * the source image.</p>
     *
     * @param width the width of the new image
     * @param height the height of the new image
     * @return a new translucent compatible <code>BufferedImage</code> of the
     *   specified width and height
     */
    public static BufferedImage createCompatibleTranslucentImage(int width,
                                                                 int height) {
        return isHeadless() ?
                new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB) :
                getGraphicsConfiguration().createCompatibleImage(width, height,
                                                   Transparency.TRANSLUCENT);
    }

    private static boolean isHeadless() {
        return GraphicsEnvironment.isHeadless();
    }

    // Returns the graphics configuration for the primary screen
    private static GraphicsConfiguration getGraphicsConfiguration() {
        return GraphicsEnvironment.getLocalGraphicsEnvironment().
                    getDefaultScreenDevice().getDefaultConfiguration();
    }

}