View Javadoc
1   /*
2    * Copyright (c) 2002-2026 Gargoyle Software Inc.
3    *
4    * Licensed under the Apache License, Version 2.0 (the "License");
5    * you may not use this file except in compliance with the License.
6    * You may obtain a copy of the License at
7    * https://www.apache.org/licenses/LICENSE-2.0
8    *
9    * Unless required by applicable law or agreed to in writing, software
10   * distributed under the License is distributed on an "AS IS" BASIS,
11   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12   * See the License for the specific language governing permissions and
13   * limitations under the License.
14   */
15  package org.htmlunit.platform.image;
16  
17  import java.io.IOException;
18  import java.io.InputStream;
19  import java.lang.ref.Cleaner;
20  import java.util.Iterator;
21  
22  import javax.imageio.ImageIO;
23  import javax.imageio.ImageReader;
24  import javax.imageio.stream.ImageInputStream;
25  
26  import org.htmlunit.WebClient;
27  import org.htmlunit.platform.geom.IntDimension2D;
28  
29  /**
30   * <span style="color:red">INTERNAL API - SUBJECT TO CHANGE AT ANY TIME - USE AT YOUR OWN RISK.</span><br>
31   *
32   * Wraps the ImageReader for an HtmlImage. This is necessary because an object with a finalize()
33   * method is only garbage collected after the method has been run. Which causes all referenced
34   * objects to also not be garbage collected until this happens. Because a HtmlImage references a lot
35   * of objects which could all be garbage collected without impacting the ImageReader it is better to
36   * wrap it in another class.
37   *
38   * @author Mike Bowler
39   * @author David K. Taylor
40   * @author Christian Sell
41   * @author Ahmed Ashour
42   * @author Knut Johannes Dahle
43   * @author Ronald Brill
44   * @author Frank Danek
45   * @author Carsten Steul
46   * @author Alex Gorbatovsky
47   */
48  public class ImageIOImageData implements ImageData {
49  
50      // private static final Log LOG = LogFactory.getLog(ImageIOImageData.class);
51  
52      private IntDimension2D dim_;
53  
54      private final ImageIOImageDataCleaningAction cleaningAction_;
55      private final Cleaner.Cleanable cleanable_;
56  
57      // private class; no one else can lock on an instance, therefore method level synchronization is fine here
58      @SuppressWarnings("PMD.AvoidSynchronizedAtMethodLevel")
59      private static final class ImageIOImageDataCleaningAction implements Runnable {
60          private ImageReader imageReader_;
61          private InputStream inputStream_;
62  
63          ImageIOImageDataCleaningAction(final ImageReader imageReader, final InputStream inputStream) {
64              imageReader_ = imageReader;
65              inputStream_ = inputStream;
66          }
67  
68          synchronized ImageReader getImageReader() {
69              if (imageReader_ == null) {
70                  throw new IllegalStateException("ImageIOImageData is closed");
71              }
72              return imageReader_;
73          }
74  
75          @Override
76          public synchronized void run() {
77              if (imageReader_ == null) {
78                  return;
79              }
80  
81              try (ImageInputStream stream = (ImageInputStream) imageReader_.getInput()) {
82                  // nothing
83              }
84              catch (final IOException e) {
85                  // optionally log
86              }
87              finally {
88                  imageReader_.setInput(null);
89                  imageReader_.dispose();
90                  imageReader_ = null;
91              }
92  
93              try {
94                  inputStream_.close();
95              }
96              catch (final IOException e) {
97                  // optionally log
98              }
99              finally {
100                 inputStream_ = null;
101             }
102         }
103     }
104 
105     /**
106      * Ctor.
107      * @param inputStream the {@link InputStream} to read from
108      * @throws IOException in case of error
109      */
110     public ImageIOImageData(final InputStream inputStream) throws IOException {
111         final ImageInputStream iis = ImageIO.createImageInputStream(inputStream);
112         final Iterator<ImageReader> iter = ImageIO.getImageReaders(iis);
113         if (!iter.hasNext()) {
114             iis.close();
115             inputStream.close();
116             throw new IOException("No image detected in response");
117         }
118 
119         final ImageReader imageReader = iter.next();
120         imageReader.setInput(iis);
121 
122         cleaningAction_ = new ImageIOImageDataCleaningAction(imageReader, inputStream);
123         cleanable_ = WebClient.registerCleanerAction(this, cleaningAction_);
124 
125         // dispose all others
126         while (iter.hasNext()) {
127             iter.next().dispose();
128         }
129     }
130 
131     /**
132      * Returns the {@link ImageReader}.
133      *
134      * @return the {@link ImageReader}
135      */
136     public ImageReader getImageReader() {
137         return cleaningAction_.getImageReader();
138     }
139 
140     /**
141      * {@inheritDoc}
142      */
143     @Override
144     public IntDimension2D getWidthHeight() throws IOException {
145         if (dim_ == null) {
146             final ImageReader imgReader = cleaningAction_.getImageReader();
147             dim_ = new IntDimension2D(imgReader.getWidth(0), imgReader.getHeight(0));
148         }
149         return dim_;
150     }
151 
152     /**
153      * {@inheritDoc}
154      */
155     @Override
156     public void close() {
157         cleanable_.clean();
158     }
159 }