IdentifiantMot de passe
Loading...
Mot de passe oublié ?Je m'inscris ! (gratuit)
Navigation

Inscrivez-vous gratuitement
pour pouvoir participer, suivre les réponses en temps réel, voter pour les messages, poser vos propres questions et recevoir la newsletter

Multimédia Java Discussion :

programme pour réduire la résolution d'une image


Sujet :

Multimédia Java

  1. #1
    Membre actif
    Inscrit en
    Juin 2005
    Messages
    303
    Détails du profil
    Informations forums :
    Inscription : Juin 2005
    Messages : 303
    Points : 201
    Points
    201
    Par défaut programme pour réduire la résolution d'une image
    existe il un programme Java pour réduire la résolution d'une image?!

    Si quelqu'un a déja rencontré ce genre de programme qu'il n'hésite pas surtout.

    Merci

  2. #2
    Membre expert
    Avatar de ®om
    Profil pro
    Inscrit en
    Janvier 2005
    Messages
    2 815
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Janvier 2005
    Messages : 2 815
    Points : 3 080
    Points
    3 080
    Par défaut
    Une classe que je me suis faite, tu peux t'en inspirer:
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    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
    package org.myfreetv.view.util;
     
    import java.awt.Color;
    import java.awt.Graphics;
    import java.awt.Graphics2D;
    import java.awt.GraphicsConfiguration;
    import java.awt.GraphicsEnvironment;
    import java.awt.Image;
    import java.awt.RenderingHints;
    import java.awt.Transparency;
    import java.awt.image.BufferedImage;
     
    import javax.swing.Icon;
    import javax.swing.ImageIcon;
     
    /**
     * Utilitaires pour les images.
     * 
     * @author rom1v
     */
    public class ImageUtilities {
     
        /** Configuration graphique, pour optimiser les images par la carte graphique. */
        private static GraphicsConfiguration graphicsConfiguration = GraphicsEnvironment.getLocalGraphicsEnvironment().getDefaultScreenDevice().getDefaultConfiguration();
     
        /** Couleur transparente. */
        public static final Color TRANSPARENCY = new Color(0, 0, 0, 0);
     
        /** Interdiction d'instancier. */
        private ImageUtilities() {}
     
        /**
         * Retourne une icône à partir d'une image. Si l'image est {@code null}, cette méthode retourne {@code null}.
         * 
         * @param image
         *            Image source.
         * @return Icône générée à partir de l'image.
         */
        public static Icon toIcon(Image image) {
            return image != null ? new ImageIcon(image) : null;
        }
     
        /**
         * Retourne une image à partir d'une icône. Si l'icône est {@code null}, cette méthode retourne {@code null}.
         * 
         * @param icon
         *            Icône source.
         * @return Image générée à partir de l'icône.
         */
        public static Image toImage(Icon icon) {
            Image result;
            if(icon == null)
                result = null;
            else {
                if(icon instanceof ImageIcon) {
                    result = ((ImageIcon) icon).getImage();
                } else {
                    int w = icon.getIconWidth();
                    int h = icon.getIconHeight();
                    BufferedImage buf = new BufferedImage(w, h, BufferedImage.TYPE_INT_ARGB);
                    icon.paintIcon(null, buf.createGraphics(), w, h);
                    result = buf;
                }
            }
            return result;
        }
     
        /**
         * Retourne l'image source aux dimensions demandées. Si la source est {@code null}, cette méthode retourne
         * {@code null}.
         * <p>
         * Si la nouvelle taille est plus grande, aussi bien en largeur qu'en hauteur, que la taille de l'image source,
         * l'image source est simplement centrée dans une image plus grande.
         * <p>
         * Si la nouvelle taille est strictement identique à la taille de l'image source, l'image source est renvoyée.
         * <p>
         * Si la nouvelle taille est plus petite que l'image source, soit en hauteur, soit en largeur, alors l'image est
         * redimensionnée tout en conservant l'aspect-ratio.
         * 
         * @param source
         *            Image source.
         * @param width
         *            Nouvelle largeur, {@code null} signifie taille optimale.
         * @param height
         *            Nouvelle hauteur, {@code null} signifie taille optimale.
         * @return Image redimensionnée.
         */
        public static Image scale(Image source, Integer width, Integer height) {
            // assert source != null : "L'image source ne doit pas être null.";
            assert width == null || width >= 0 : "La largeur doit être positive.";
            assert height == null || height >= 0 : "La hauteur doit être positive.";
     
            Image result = null;
            if(source != null) {
                /* Taille de l'image source. */
                int sourceWidth = source.getWidth(null);
                int sourceHeight = source.getHeight(null);
     
                // /* Width et height prennent la taille indiquée, si elle est nulle ils prennent la taille optimale. */
                // int width = widthDim != null ? widthDim : sourceWidth;
                // int height = heightDim != null ? heightDim : sourceHeight;
     
                if((width == null || sourceWidth == width) && (height == null || sourceHeight == height)) {
                    /* Si les dimensions sont déjà correctes, on ne redimensionne pas. */
                    result = source;
                } else {
     
                    /* Largeur de l'image réelle. */
                    int w;
                    /* Hauteur de l'image réelle. */
                    int h;
     
                    if((width != null && width < sourceWidth) || (height != null && height < sourceHeight)) {
                        /* Si l'image source a besoin d'être rétrécie. */
     
                        /* On calcule les ratio pour chaque dimension de la nouvelle image par rapport à la source. */
                        Double widthRatio = width != null ? ((double) width) / sourceWidth : null;
                        Double heightRatio = height != null ? ((double) height) / sourceHeight : null;
     
                        /* Le plus petit ratio des deux est la dimension limitante. */
                        double newRatio;
                        if(widthRatio == null) {
                            /* On est alors sûr que heightRatio n'est pas null (premier test de boucle). */
                            assert heightRatio != null : "heightRatio ne doit pas être null.";
                            newRatio = heightRatio;
                        } else {
                            if(heightRatio == null) {
                                newRatio = widthRatio;
                            } else {
                                newRatio = Math.min(widthRatio, heightRatio);
                            }
                        }
     
                        /* On calcule les dimensions réelles de l'image destination, que l'on va centrer dans le résultat. */
                        w = (int) (sourceWidth * newRatio);
                        h = (int) (sourceHeight * newRatio);
                    } else {
                        /* Les dimensions réelles de l'image sont celles de la source. */
                        w = sourceWidth;
                        h = sourceHeight;
                    }
     
                    /*
                     * Si width ou height étaient null, on les initialise avec la valeur optimale. Les 2 ne peuvent pas être
                     * null en même temps à ce stade.
                     */
                    if(width == null)
                        width = w;
                    else if(height == null)
                        height = h;
     
                    /*
                     * On centre maintenant l'image source (éventuellement rétrécie) dans l'image destination. Pour cela, on
                     * calcule les coordonnées du coin haut-gauche de l'image réelle par rapport à l'image destination.
                     * width et height sont forcément non null.
                     */
                    int x = (width - w) / 2;
                    int y = (height - h) / 2;
     
                    /* On crée une nouvelle image aux bonnes dimensions. */
                    BufferedImage buf = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
     
                    /* On dessine sur l'image bufferisée. */
                    Graphics2D g = buf.createGraphics();
                    g.setBackground(TRANSPARENCY);
                    g.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
                    g.drawImage(source, x, y, w, h, null);
                    g.dispose();
     
                    result = buf;
                }
            }
            return result;
        }
     
        /**
         * Crée une image compatible avec la carte graphique (améliore les performances d'affichage.
         * 
         * @param image
         *            Image à rendre compatible.
         * @return Image compatible.
         */
        public static BufferedImage toCompatibleImage(Image image) {
            BufferedImage compatibleImage = graphicsConfiguration.createCompatibleImage(image.getWidth(null), image.getHeight(null), Transparency.TRANSLUCENT);
            Graphics g = compatibleImage.getGraphics();
            g.drawImage(image, 0, 0, null);
            g.dispose();
            return compatibleImage;
        }
     
    }

  3. #3
    Membre actif
    Inscrit en
    Juin 2005
    Messages
    303
    Détails du profil
    Informations forums :
    Inscription : Juin 2005
    Messages : 303
    Points : 201
    Points
    201
    Par défaut
    Merci

    Je vais tester et je te tiens au courrant.

  4. #4
    Gfx
    Gfx est déconnecté
    Expert éminent
    Avatar de Gfx
    Inscrit en
    Mai 2005
    Messages
    1 770
    Détails du profil
    Informations personnelles :
    Âge : 42

    Informations forums :
    Inscription : Mai 2005
    Messages : 1 770
    Points : 8 178
    Points
    8 178
    Par défaut
    Tu peux aussi utiliser la classe GraphicsUtilities du projet SwingX qui contient tout un tas de méthodes pour faire cela, suivant que tu privilégies la qualité ou la rapidité.

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    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
    427
    428
    429
    430
    431
    432
    433
    434
    435
    436
    437
    438
    439
    440
    441
    442
    443
    444
    445
    446
    447
    448
    449
    450
    451
    452
    453
    454
    455
    456
    457
    458
    459
    460
    461
    462
    463
    464
    465
    466
    467
    468
    469
    470
    471
    472
    473
    474
    475
    476
    477
    478
    479
    480
    481
    482
    483
    484
    485
    486
    487
    488
    489
    490
    491
    492
    493
    494
    495
    496
    497
    498
    499
    500
    501
    502
    503
    504
    505
    506
    507
    508
    509
    510
    511
    512
    513
    514
    515
    516
    517
    518
    519
    520
    521
    522
    523
    524
    525
    526
    527
    528
    529
    530
    531
    532
    533
    534
    535
    536
    537
    538
    539
    540
    541
    542
    543
    544
    545
    546
    547
    548
    549
    550
    551
    552
    553
    554
    555
    556
    557
    558
    559
     
    /*
     * $Id: GraphicsUtilities.java,v 1.1 2006/10/22 03:26:23 gfx Exp $
     *
     * Dual-licensed under LGPL (Sun and Romain Guy) and BSD (Romain Guy).
     *
     * Copyright 2005 Sun Microsystems, Inc., 4150 Network Circle,
     * Santa Clara, California 95054, U.S.A. All rights reserved.
     *
     * Copyright (c) 2006 Romain Guy <romain.guy@mac.com>
     * All rights reserved.
     *
     * Redistribution and use in source and binary forms, with or without
     * modification, are permitted provided that the following conditions
     * are met:
     * 1. Redistributions of source code must retain the above copyright
     *    notice, this list of conditions and the following disclaimer.
     * 2. Redistributions in binary form must reproduce the above copyright
     *    notice, this list of conditions and the following disclaimer in the
     *    documentation and/or other materials provided with the distribution.
     * 3. The name of the author may not be used to endorse or promote products
     *    derived from this software without specific prior written permission.
     *
     * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
     * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
     * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
     * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
     * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
     * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
     * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
     * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
     * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
     * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
     */
     
    package org.jdesktop.swingx.graphics;
     
    import java.awt.image.BufferedImage;
    import java.awt.image.ColorModel;
    import java.awt.image.Raster;
    import java.awt.image.WritableRaster;
    import java.awt.GraphicsConfiguration;
    import java.awt.Transparency;
    import java.awt.Graphics;
    import java.awt.GraphicsEnvironment;
    import java.awt.Graphics2D;
    import java.awt.RenderingHints;
    import java.io.IOException;
    import java.net.URL;
    import javax.imageio.ImageIO;
     
    /**
     * <p><code>GraphicsUtilities</code> contains a set of tools to perform
     * common graphics operations easily. These operations are divided into
     * several themes, listed below.</p>
     * <h2>Compatible Images</h2>
     * <p>Compatible images can, and should, be used to increase drawing
     * performance. This class provides a number of methods to load compatible
     * images directly from files or to convert existing images to compatibles
     * images.</p>
     * <h2>Creating Thumbnails</h2>
     * <p>This class provides a number of methods to easily scale down images.
     * Some of these methods offer a trade-off between speed and result quality and
     * shouuld be used all the time. They also offer the advantage of producing
     * compatible images, thus automatically resulting into better runtime
     * performance.</p>
     * <p>All these methodes are both faster than
     * {@link java.awt.Image#getScaledInstance(int, int, int)} and produce
     * better-looking results than the various <code>drawImage()</code> methods
     * in {@link java.awt.Graphics}, which can be used for image scaling.</p>
     * <h2>Image Manipulation</h2>
     * <p>This class provides two methods to get and set pixels in a buffered image.
     * These methods try to avoid unmanaging the image in order to keep good
     * performance.</p>
     *
     * @author Romain Guy <romain.guy@mac.com>
     */
    public class GraphicsUtilities {
        private static final GraphicsConfiguration CONFIGURATION =
                GraphicsEnvironment.getLocalGraphicsEnvironment().
                        getDefaultScreenDevice().getDefaultConfiguration();
     
        private GraphicsUtilities() {
        }
     
        /**
         * <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 compatible image with the same width, height and
         * transparency as the image specified as a parameter.</p>
         *
         * @see java.awt.Transparency
         * @see #createCompatibleImage(int, int)
         * @see #createCompatibleImage(java.awt.image.BufferedImage, int, int)
         * @see #createTranslucentCompatibleImage(int, int)
         * @see #loadCompatibleImage(java.net.URL)
         * @see #toCompatibleImage(java.awt.image.BufferedImage)
         * @param image the reference image from which the dimension and the
         *   transparency of the new image are obtained
         * @return a new compatible <code>BufferedImage</code> with the same
         *   dimension and transparency as <code>image</code>
         */
        public static BufferedImage createCompatibleImage(BufferedImage image) {
            return createCompatibleImage(image, image.getWidth(), image.getHeight());
        }
     
        /**
         * <p>Returns a new compatible image of the specified width and height, and
         * the same transparency setting as the image specified as a parameter.</p>
         *
         * @see java.awt.Transparency
         * @see #createCompatibleImage(java.awt.image.BufferedImage)
         * @see #createCompatibleImage(int, int)
         * @see #createTranslucentCompatibleImage(int, int)
         * @see #loadCompatibleImage(java.net.URL)
         * @see #toCompatibleImage(java.awt.image.BufferedImage)
         * @param width the width of the new image
         * @param height the height of the new image
         * @param image the reference image from which the transparency of the new
         *   image is obtained
         * @return a new compatible <code>BufferedImage</code> with the same
         *   transparency as <code>image</code> and the specified dimension
         */
        public static BufferedImage createCompatibleImage(BufferedImage image,
                                                          int width, int height) {
            return CONFIGURATION.createCompatibleImage(width, height,
                                                       image.getTransparency());
        }
     
        /**
         * <p>Returns a new opaque compatible image of the specified width and
         * height.</p>
         *
         * @see #createCompatibleImage(java.awt.image.BufferedImage)
         * @see #createCompatibleImage(java.awt.image.BufferedImage, int, int)
         * @see #createTranslucentCompatibleImage(int, int)
         * @see #loadCompatibleImage(java.net.URL)
         * @see #toCompatibleImage(java.awt.image.BufferedImage)
         * @param width the width of the new image
         * @param height the height of the new image
         * @return a new opaque compatible <code>BufferedImage</code> of the
         *   specified width and height
         */
        public static BufferedImage createCompatibleImage(int width, int height) {
            return CONFIGURATION.createCompatibleImage(width, height);
        }
     
        /**
         * <p>Returns a new translucent compatible image of the specified width
         * and height.</p>
         *
         * @see #createCompatibleImage(java.awt.image.BufferedImage)
         * @see #createCompatibleImage(java.awt.image.BufferedImage, int, int)
         * @see #createCompatibleImage(int, int)
         * @see #loadCompatibleImage(java.net.URL)
         * @see #toCompatibleImage(java.awt.image.BufferedImage)
         * @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 createTranslucentCompatibleImage(int width,
                                                                     int height) {
            return CONFIGURATION.createCompatibleImage(width, height,
                                                       Transparency.TRANSLUCENT);
        }
     
        /**
         * <p>Returns a new compatible image from a URL. The image is loaded from the
         * specified location and then turned, if necessary into a compatible
         * image.</p>
         *
         * @see #createCompatibleImage(java.awt.image.BufferedImage)
         * @see #createCompatibleImage(java.awt.image.BufferedImage, int, int)
         * @see #createCompatibleImage(int, int)
         * @see #createTranslucentCompatibleImage(int, int)
         * @see #toCompatibleImage(java.awt.image.BufferedImage)
         * @param resource the URL of the picture to load as a compatible image
         * @return a new translucent compatible <code>BufferedImage</code> of the
         *   specified width and height
         * @throws java.io.IOException if the image cannot be read or loaded
         */
        public static BufferedImage loadCompatibleImage(URL resource)
                throws IOException {
            BufferedImage image = ImageIO.read(resource);
            return toCompatibleImage(image);
        }
     
        /**
         * <p>Return a new compatible image that contains a copy of the specified
         * image. This method ensures an image is compatible with the hardware,
         * and therefore optimized for fast blitting operations.</p>
         *
         * @see #createCompatibleImage(java.awt.image.BufferedImage)
         * @see #createCompatibleImage(java.awt.image.BufferedImage, int, int)
         * @see #createCompatibleImage(int, int)
         * @see #createTranslucentCompatibleImage(int, int)
         * @see #loadCompatibleImage(java.net.URL)
         * @param image the image to copy into a new compatible image
         * @return a new compatible copy, with the
         *   same width and height and transparency and content, of <code>image</code>
         */
        public static BufferedImage toCompatibleImage(BufferedImage image) {
            if (image.getColorModel().equals(CONFIGURATION.getColorModel())) {
                return image;
            }
     
            BufferedImage compatibleImage = CONFIGURATION.createCompatibleImage(
                    image.getWidth(), image.getHeight(), image.getTransparency());
            Graphics g = compatibleImage.getGraphics();
            g.drawImage(image, 0, 0, null);
            g.dispose();
     
            return compatibleImage;
        }
     
        /**
         * <p>Returns a thumbnail of a source image. <code>newSize</code> defines
         * the length of the longest dimension of the thumbnail. The other
         * dimension is then computed according to the dimensions ratio of the
         * original picture.</p>
         * <p>This method favors speed over quality. When the new size is less than
         * half the longest dimension of the source image,
         * {@link #createThumbnail(BufferedImage, int)} or
         * {@link #createThumbnail(BufferedImage, int, int)} should be used instead
         * to ensure the quality of the result without sacrificing too much
         * performance.</p>
         *
         * @see #createThumbnailFast(java.awt.image.BufferedImage, int, int)
         * @see #createThumbnail(java.awt.image.BufferedImage, int)
         * @see #createThumbnail(java.awt.image.BufferedImage, int, int)
         * @param image the source image
         * @param newSize the length of the largest dimension of the thumbnail
         * @return a new compatible <code>BufferedImage</code> containing a
         *   thumbnail of <code>image</code>
         * @throws IllegalArgumentException if <code>newSize</code> is larger than
         *   the largest dimension of <code>image</code> or &lt;= 0
         */
        public static BufferedImage createThumbnailFast(BufferedImage image,
                                                        int newSize) {
            float ratio;
            int width = image.getWidth();
            int height = image.getHeight();
     
            if (width > height) {
                if (newSize >= width) {
                    throw new IllegalArgumentException("newSize must be lower than" +
                                                       " the image width");
                } else if (newSize <= 0) {
                     throw new IllegalArgumentException("newSize must" +
                                                        " be greater than 0");
                }
     
                ratio = (float) width / (float) height;
                width = newSize;
                height = (int) (newSize / ratio);
            } else {
                if (newSize >= height) {
                    throw new IllegalArgumentException("newSize must be lower than" +
                                                       " the image height");
                } else if (newSize <= 0) {
                     throw new IllegalArgumentException("newSize must" +
                                                        " be greater than 0");
                }
     
                ratio = (float) height / (float) width;
                height = newSize;
                width = (int) (newSize / ratio);
            }
     
            BufferedImage temp = createCompatibleImage(image, width, height);
            Graphics2D g2 = temp.createGraphics();
            g2.setRenderingHint(RenderingHints.KEY_INTERPOLATION,
                                RenderingHints.VALUE_INTERPOLATION_BILINEAR);
            g2.drawImage(image, 0, 0, temp.getWidth(), temp.getHeight(), null);
            g2.dispose();
     
            return temp;
        }
     
        /**
         * <p>Returns a thumbnail of a source image.</p>
         * <p>This method favors speed over quality. When the new size is less than
         * half the longest dimension of the source image,
         * {@link #createThumbnail(BufferedImage, int)} or
         * {@link #createThumbnail(BufferedImage, int, int)} should be used instead
         * to ensure the quality of the result without sacrificing too much
         * performance.</p>
         *
         * @see #createThumbnailFast(java.awt.image.BufferedImage, int)
         * @see #createThumbnail(java.awt.image.BufferedImage, int)
         * @see #createThumbnail(java.awt.image.BufferedImage, int, int)
         * @param image the source image
         * @param newWidth the width of the thumbnail
         * @param newHeight the height of the thumbnail
         * @return a new compatible <code>BufferedImage</code> containing a
         *   thumbnail of <code>image</code>
         * @throws IllegalArgumentException if <code>newWidth</code> is larger than
         *   the width of <code>image</code> or if code>newHeight</code> is larger
         *   than the height of <code>image</code> or if one of the dimensions
         *   is &lt;= 0
         */
        public static BufferedImage createThumbnailFast(BufferedImage image,
                                                        int newWidth, int newHeight) {
            if (newWidth >= image.getWidth() ||
                newHeight >= image.getHeight()) {
                throw new IllegalArgumentException("newWidth and newHeight cannot" +
                                                   " be greater than the image" +
                                                   " dimensions");
            } else if (newWidth <= 0 || newHeight <= 0) {
                throw new IllegalArgumentException("newWidth and newHeight must" +
                                                   " be greater than 0");
            }
     
            BufferedImage temp = createCompatibleImage(image, newWidth, newHeight);
            Graphics2D g2 = temp.createGraphics();
            g2.setRenderingHint(RenderingHints.KEY_INTERPOLATION,
                                RenderingHints.VALUE_INTERPOLATION_BILINEAR);
            g2.drawImage(image, 0, 0, temp.getWidth(), temp.getHeight(), null);
            g2.dispose();
     
            return temp;
        }
     
        /**
         * <p>Returns a thumbnail of a source image. <code>newSize</code> defines
         * the length of the longest dimension of the thumbnail. The other
         * dimension is then computed according to the dimensions ratio of the
         * original picture.</p>
         * <p>This method offers a good trade-off between speed and quality.
         * The result looks better than
         * {@link #createThumbnailFast(java.awt.image.BufferedImage, int)} when
         * the new size is less than half the longest dimension of the source
         * image, yet the rendering speed is almost similar.</p>
         *
         * @see #createThumbnailFast(java.awt.image.BufferedImage, int, int)
         * @see #createThumbnailFast(java.awt.image.BufferedImage, int)
         * @see #createThumbnail(java.awt.image.BufferedImage, int, int)
         * @param image the source image
         * @param newSize the length of the largest dimension of the thumbnail
         * @return a new compatible <code>BufferedImage</code> containing a
         *   thumbnail of <code>image</code>
         * @throws IllegalArgumentException if <code>newSize</code> is larger than
         *   the largest dimension of <code>image</code> or &lt;= 0
         */
        public static BufferedImage createThumbnail(BufferedImage image,
                                                    int newSize) {
            int width = image.getWidth();
            int height = image.getHeight();
     
            boolean isWidthGreater = width > height;
     
            if (isWidthGreater) {
                if (newSize >= width) {
                    throw new IllegalArgumentException("newSize must be lower than" +
                                                       " the image width");
                }
            } else if (newSize >= height) {
                throw new IllegalArgumentException("newSize must be lower than" +
                                                   " the image height");
            }
     
            if (newSize <= 0) {
                throw new IllegalArgumentException("newSize must" +
                                                   " be greater than 0");
            }
     
            float ratioWH = (float) width / (float) height;
            float ratioHW = (float) height / (float) width;
     
            BufferedImage thumb = image;
     
            do {
                if (isWidthGreater) {
                    width /= 2;
                    if (width < newSize) {
                        width = newSize;
                    }
                    height = (int) (width / ratioWH);
                } else {
                    height /= 2;
                    if (height < newSize) {
                        height = newSize;
                    }
                    width = (int) (height / ratioHW);
                }
     
     
                BufferedImage temp = createCompatibleImage(image, width, height);
                Graphics2D g2 = temp.createGraphics();
                g2.setRenderingHint(RenderingHints.KEY_INTERPOLATION,
                                    RenderingHints.VALUE_INTERPOLATION_BILINEAR);
                g2.drawImage(thumb, 0, 0, temp.getWidth(), temp.getHeight(), null);
                g2.dispose();
     
                thumb = temp;
            } while (newSize != (isWidthGreater ? width : height));
     
            return thumb;
        }
     
        /**
         * <p>Returns a thumbnail of a source image.</p>
         * <p>This method offers a good trade-off between speed and quality.
         * The result looks better than
         * {@link #createThumbnailFast(java.awt.image.BufferedImage, int)} when
         * the new size is less than half the longest dimension of the source
         * image, yet the rendering speed is almost similar.</p>
         *
         * @see #createThumbnailFast(java.awt.image.BufferedImage, int)
         * @see #createThumbnailFast(java.awt.image.BufferedImage, int, int)
         * @see #createThumbnail(java.awt.image.BufferedImage, int)
         * @param image the source image
         * @param newWidth the width of the thumbnail
         * @param newHeight the height of the thumbnail
         * @return a new compatible <code>BufferedImage</code> containing a
         *   thumbnail of <code>image</code>
         * @throws IllegalArgumentException if <code>newWidth</code> is larger than
         *   the width of <code>image</code> or if code>newHeight</code> is larger
         *   than the height of <code>image or if one the dimensions is not &gt; 0</code>
         */
        public static BufferedImage createThumbnail(BufferedImage image,
                                                    int newWidth, int newHeight) {
            int width = image.getWidth();
            int height = image.getHeight();
     
            if (newWidth >= width || newHeight >= height) {
                throw new IllegalArgumentException("newWidth and newHeight cannot" +
                                                   " be greater than the image" +
                                                   " dimensions");
            } else if (newWidth <= 0 || newHeight <= 0) {
                throw new IllegalArgumentException("newWidth and newHeight must" +
                                                   " be greater than 0");
            }
     
            BufferedImage thumb = image;
     
            do {
                if (width > newWidth) {
                    width /= 2;
                    if (width < newWidth) {
                        width = newWidth;
                    }
                }
     
                if (height > newHeight) {
                    height /= 2;
                    if (height < newHeight) {
                        height = newHeight;
                    }
                }
     
                BufferedImage temp = createCompatibleImage(image, width, height);
                Graphics2D g2 = temp.createGraphics();
                g2.setRenderingHint(RenderingHints.KEY_INTERPOLATION,
                                    RenderingHints.VALUE_INTERPOLATION_BILINEAR);
                g2.drawImage(thumb, 0, 0, temp.getWidth(), temp.getHeight(), null);
                g2.dispose();
     
                thumb = temp;
            } while (width != newWidth || height != newHeight);
     
            return thumb;
        }
     
        /**
         * <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);
            }
        }
    }

  5. #5
    Gfx
    Gfx est déconnecté
    Expert éminent
    Avatar de Gfx
    Inscrit en
    Mai 2005
    Messages
    1 770
    Détails du profil
    Informations personnelles :
    Âge : 42

    Informations forums :
    Inscription : Mai 2005
    Messages : 1 770
    Points : 8 178
    Points
    8 178
    Par défaut
    ®om : Il y a plusieurs choses inutiles dans ton code. Au lieu d'utiliser des Double, tu peux utiliser des double et leur donner 0 au lieu de null. Une image ne peut pas avoir une dimension égale à 0. Tu pourrais aussi donner -1 comme valeur. Bref, évite des objets inutiles.

    Ensuite la ligne suivante est rigoureusement inutile :

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    g.setBackground(TRANSPARENCY);
    Note enfin que créer toujours une image de type TYPE_INT_ARGB ne signifie pas qu'elle sera compatible sur toutes les plateformes.

  6. #6
    Membre actif
    Inscrit en
    Juin 2005
    Messages
    303
    Détails du profil
    Informations forums :
    Inscription : Juin 2005
    Messages : 303
    Points : 201
    Points
    201
    Par défaut
    Citation Envoyé par Gfx
    ®om : Il y a plusieurs choses inutiles dans ton code. Au lieu d'utiliser des Double, tu peux utiliser des double et leur donner 0 au lieu de null. Une image ne peut pas avoir une dimension égale à 0. Tu pourrais aussi donner -1 comme valeur. Bref, évite des objets inutiles.

    Ensuite la ligne suivante est rigoureusement inutile :

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    g.setBackground(TRANSPARENCY);
    Note enfin que créer toujours une image de type TYPE_INT_ARGB ne signifie pas qu'elle sera compatible sur toutes les plateformes.
    En effet, elle fonctionne très bien cette classe. Merci

  7. #7
    Membre expert
    Avatar de ®om
    Profil pro
    Inscrit en
    Janvier 2005
    Messages
    2 815
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Janvier 2005
    Messages : 2 815
    Points : 3 080
    Points
    3 080
    Par défaut
    Citation Envoyé par Gfx
    ®om : Il y a plusieurs choses inutiles dans ton code. Au lieu d'utiliser des Double, tu peux utiliser des double et leur donner 0 au lieu de null. Une image ne peut pas avoir une dimension égale à 0. Tu pourrais aussi donner -1 comme valeur. Bref, évite des objets inutiles.
    Oauis... je verrai ça...

    Citation Envoyé par Gfx
    Ensuite la ligne suivante est rigoureusement inutile
    OK, je l'enlève dans mon code...

    Citation Envoyé par Gfx
    Note enfin que créer toujours une image de type TYPE_INT_ARGB ne signifie pas qu'elle sera compatible sur toutes les plateformes.
    Comment ça?



    Merci de tes remarques

    EDIT: une autre question, est-ce que la classe que tu as postée, quand tu redimensionnes, elle garde le ratio ou pas?

    (par exemple une image 8-4, tu veux la passer en 4-4 (donc applatie), elle passe en 4-2 ou se déforme en 4-4)?

+ Répondre à la discussion
Cette discussion est résolue.

Discussions similaires

  1. Réponses: 2
    Dernier message: 04/05/2015, 19h54
  2. Utiliser l'api GDi+ pour réduire la taille d'une image
    Par deepshark dans le forum WinDev
    Réponses: 3
    Dernier message: 04/06/2010, 09h31
  3. Résolution d'une image pour impression
    Par titinesaku dans le forum Langage
    Réponses: 4
    Dernier message: 28/04/2009, 10h50
  4. réduire la résolution d'une image
    Par laurentSc dans le forum Imagerie
    Réponses: 3
    Dernier message: 05/03/2009, 19h34
  5. résolution d'une image
    Par nabil dans le forum VB 6 et antérieur
    Réponses: 23
    Dernier message: 29/08/2005, 20h12

Partager

Partager
  • Envoyer la discussion sur Viadeo
  • Envoyer la discussion sur Twitter
  • Envoyer la discussion sur Google
  • Envoyer la discussion sur Facebook
  • Envoyer la discussion sur Digg
  • Envoyer la discussion sur Delicious
  • Envoyer la discussion sur MySpace
  • Envoyer la discussion sur Yahoo