Search in sources :

Example 11 with IIOException

use of javax.imageio.IIOException in project jdk8u_jdk by JetBrains.

the class PNGImageWriter method write.

public void write(IIOMetadata streamMetadata, IIOImage image, ImageWriteParam param) throws IIOException {
    if (stream == null) {
        throw new IllegalStateException("output == null!");
    }
    if (image == null) {
        throw new IllegalArgumentException("image == null!");
    }
    if (image.hasRaster()) {
        throw new UnsupportedOperationException("image has a Raster!");
    }
    RenderedImage im = image.getRenderedImage();
    SampleModel sampleModel = im.getSampleModel();
    this.numBands = sampleModel.getNumBands();
    // Set source region and subsampling to default values
    this.sourceXOffset = im.getMinX();
    this.sourceYOffset = im.getMinY();
    this.sourceWidth = im.getWidth();
    this.sourceHeight = im.getHeight();
    this.sourceBands = null;
    this.periodX = 1;
    this.periodY = 1;
    if (param != null) {
        // Get source region and subsampling factors
        Rectangle sourceRegion = param.getSourceRegion();
        if (sourceRegion != null) {
            Rectangle imageBounds = new Rectangle(im.getMinX(), im.getMinY(), im.getWidth(), im.getHeight());
            // Clip to actual image bounds
            sourceRegion = sourceRegion.intersection(imageBounds);
            sourceXOffset = sourceRegion.x;
            sourceYOffset = sourceRegion.y;
            sourceWidth = sourceRegion.width;
            sourceHeight = sourceRegion.height;
        }
        // Adjust for subsampling offsets
        int gridX = param.getSubsamplingXOffset();
        int gridY = param.getSubsamplingYOffset();
        sourceXOffset += gridX;
        sourceYOffset += gridY;
        sourceWidth -= gridX;
        sourceHeight -= gridY;
        // Get subsampling factors
        periodX = param.getSourceXSubsampling();
        periodY = param.getSourceYSubsampling();
        int[] sBands = param.getSourceBands();
        if (sBands != null) {
            sourceBands = sBands;
            numBands = sourceBands.length;
        }
    }
    // Compute output dimensions
    int destWidth = (sourceWidth + periodX - 1) / periodX;
    int destHeight = (sourceHeight + periodY - 1) / periodY;
    if (destWidth <= 0 || destHeight <= 0) {
        throw new IllegalArgumentException("Empty source region!");
    }
    // Compute total number of pixels for progress notification
    this.totalPixels = destWidth * destHeight;
    this.pixelsDone = 0;
    // Create metadata
    IIOMetadata imd = image.getMetadata();
    if (imd != null) {
        metadata = (PNGMetadata) convertImageMetadata(imd, ImageTypeSpecifier.createFromRenderedImage(im), null);
    } else {
        metadata = new PNGMetadata();
    }
    if (param != null) {
        // Use Adam7 interlacing if set in write param
        switch(param.getProgressiveMode()) {
            case ImageWriteParam.MODE_DEFAULT:
                metadata.IHDR_interlaceMethod = 1;
                break;
            case ImageWriteParam.MODE_DISABLED:
                metadata.IHDR_interlaceMethod = 0;
                break;
        }
    }
    // Initialize bitDepth and colorType
    metadata.initialize(new ImageTypeSpecifier(im), numBands);
    // Overwrite IHDR width and height values with values from image
    metadata.IHDR_width = destWidth;
    metadata.IHDR_height = destHeight;
    this.bpp = numBands * ((metadata.IHDR_bitDepth == 16) ? 2 : 1);
    // Initialize scaling tables for this image
    initializeScaleTables(sampleModel.getSampleSize());
    clearAbortRequest();
    processImageStarted(0);
    try {
        write_magic();
        write_IHDR();
        write_cHRM();
        write_gAMA();
        write_iCCP();
        write_sBIT();
        write_sRGB();
        write_PLTE();
        write_hIST();
        write_tRNS();
        write_bKGD();
        write_pHYs();
        write_sPLT();
        write_tIME();
        write_tEXt();
        write_iTXt();
        write_zTXt();
        writeUnknownChunks();
        write_IDAT(im);
        if (abortRequested()) {
            processWriteAborted();
        } else {
            // Finish up and inform the listeners we are done
            writeIEND();
            processImageComplete();
        }
    } catch (IOException e) {
        throw new IIOException("I/O error writing PNG file!", e);
    }
}
Also used : Rectangle(java.awt.Rectangle) IIOException(javax.imageio.IIOException) IOException(java.io.IOException) IIOException(javax.imageio.IIOException) ImageTypeSpecifier(javax.imageio.ImageTypeSpecifier) IIOMetadata(javax.imageio.metadata.IIOMetadata) SampleModel(java.awt.image.SampleModel) RenderedImage(java.awt.image.RenderedImage)

Example 12 with IIOException

use of javax.imageio.IIOException in project jdk8u_jdk by JetBrains.

the class PNGImageReader method readMetadata.

private void readMetadata() throws IIOException {
    if (gotMetadata) {
        return;
    }
    readHeader();
    /*
         * Optimization: We can skip the remaining metadata if the
         * ignoreMetadata flag is set, and only if this is not a palette
         * image (in that case, we need to read the metadata to get the
         * tRNS chunk, which is needed for the getImageTypes() method).
         */
    int colorType = metadata.IHDR_colorType;
    if (ignoreMetadata && colorType != PNG_COLOR_PALETTE) {
        try {
            while (true) {
                int chunkLength = stream.readInt();
                int chunkType = stream.readInt();
                if (chunkType == IDAT_TYPE) {
                    // We've reached the image data
                    stream.skipBytes(-8);
                    imageStartPosition = stream.getStreamPosition();
                    break;
                } else {
                    // Skip the chunk plus the 4 CRC bytes that follow
                    stream.skipBytes(chunkLength + 4);
                }
            }
        } catch (IOException e) {
            throw new IIOException("Error skipping PNG metadata", e);
        }
        gotMetadata = true;
        return;
    }
    try {
        loop: while (true) {
            int chunkLength = stream.readInt();
            int chunkType = stream.readInt();
            int chunkCRC;
            // verify the chunk length
            if (chunkLength < 0) {
                throw new IIOException("Invalid chunk lenght " + chunkLength);
            }
            ;
            try {
                stream.mark();
                stream.seek(stream.getStreamPosition() + chunkLength);
                chunkCRC = stream.readInt();
                stream.reset();
            } catch (IOException e) {
                throw new IIOException("Invalid chunk length " + chunkLength);
            }
            switch(chunkType) {
                case IDAT_TYPE:
                    // If chunk type is 'IDAT', we've reached the image data.
                    stream.skipBytes(-8);
                    imageStartPosition = stream.getStreamPosition();
                    break loop;
                case PLTE_TYPE:
                    parse_PLTE_chunk(chunkLength);
                    break;
                case bKGD_TYPE:
                    parse_bKGD_chunk();
                    break;
                case cHRM_TYPE:
                    parse_cHRM_chunk();
                    break;
                case gAMA_TYPE:
                    parse_gAMA_chunk();
                    break;
                case hIST_TYPE:
                    parse_hIST_chunk(chunkLength);
                    break;
                case iCCP_TYPE:
                    parse_iCCP_chunk(chunkLength);
                    break;
                case iTXt_TYPE:
                    if (ignoreMetadata) {
                        stream.skipBytes(chunkLength);
                    } else {
                        parse_iTXt_chunk(chunkLength);
                    }
                    break;
                case pHYs_TYPE:
                    parse_pHYs_chunk();
                    break;
                case sBIT_TYPE:
                    parse_sBIT_chunk();
                    break;
                case sPLT_TYPE:
                    parse_sPLT_chunk(chunkLength);
                    break;
                case sRGB_TYPE:
                    parse_sRGB_chunk();
                    break;
                case tEXt_TYPE:
                    parse_tEXt_chunk(chunkLength);
                    break;
                case tIME_TYPE:
                    parse_tIME_chunk();
                    break;
                case tRNS_TYPE:
                    parse_tRNS_chunk(chunkLength);
                    break;
                case zTXt_TYPE:
                    if (ignoreMetadata) {
                        stream.skipBytes(chunkLength);
                    } else {
                        parse_zTXt_chunk(chunkLength);
                    }
                    break;
                default:
                    // Read an unknown chunk
                    byte[] b = new byte[chunkLength];
                    stream.readFully(b);
                    StringBuilder chunkName = new StringBuilder(4);
                    chunkName.append((char) (chunkType >>> 24));
                    chunkName.append((char) ((chunkType >> 16) & 0xff));
                    chunkName.append((char) ((chunkType >> 8) & 0xff));
                    chunkName.append((char) (chunkType & 0xff));
                    int ancillaryBit = chunkType >>> 28;
                    if (ancillaryBit == 0) {
                        processWarningOccurred("Encountered unknown chunk with critical bit set!");
                    }
                    metadata.unknownChunkType.add(chunkName.toString());
                    metadata.unknownChunkData.add(b);
                    break;
            }
            // double check whether all chunk data were consumed
            if (chunkCRC != stream.readInt()) {
                throw new IIOException("Failed to read a chunk of type " + chunkType);
            }
            stream.flushBefore(stream.getStreamPosition());
        }
    } catch (IOException e) {
        throw new IIOException("Error reading PNG metadata", e);
    }
    gotMetadata = true;
}
Also used : IIOException(javax.imageio.IIOException) IIOException(javax.imageio.IIOException) IOException(java.io.IOException) Point(java.awt.Point)

Example 13 with IIOException

use of javax.imageio.IIOException in project OsmAnd-tools by osmandapp.

the class MapPanel method getImageFor.

public Image getImageFor(int x, int y, int zoom, boolean loadIfNeeded) throws IOException {
    if (map == null) {
        return null;
    }
    String file = getFileForImage(x, y, zoom, map.getTileFormat());
    if (cache.get(file) == null) {
        File en = new File(tilesLocation, file);
        if (cache.size() > 100) {
            ArrayList<String> list = new ArrayList<String>(cache.keySet());
            for (int i = 0; i < list.size(); i += 2) {
                Image remove = cache.remove(list.get(i));
                remove.flush();
            }
            if (log.isInfoEnabled()) {
                log.info(// $NON-NLS-1$ //$NON-NLS-2$
                "Before running gc on map tiles. Total Memory : " + (Runtime.getRuntime().totalMemory() >> 20) + " Mb. Used memory : " + ((Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory()) >> 20) + // $NON-NLS-1$
                " Mb");
            }
            System.gc();
            if (log.isInfoEnabled()) {
                log.info(// $NON-NLS-1$ //$NON-NLS-2$
                "After running gc on map tiles. Total Memory : " + (Runtime.getRuntime().totalMemory() >> 20) + " Mb. Used memory : " + ((Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory()) >> 20) + // $NON-NLS-1$
                " Mb");
            }
        }
        if (!downloader.isFileCurrentlyDownloaded(en)) {
            if (en.exists()) {
                // long time = System.currentTimeMillis();
                try {
                    cache.put(file, ImageIO.read(en));
                // if (log.isDebugEnabled()) {
                // log.debug("Loaded file : " + file + " " + (System.currentTimeMillis() - time) + " ms");
                // }
                } catch (IIOException e) {
                    // $NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
                    log.error("Eror reading png " + x + " " + y + " zoom : " + zoom, e);
                }
            }
            if (loadIfNeeded && cache.get(file) == null) {
                String urlToLoad = map.getUrlToLoad(x, y, zoom);
                if (urlToLoad != null) {
                    downloader.requestToDownload(new DownloadRequest(urlToLoad, en, x, y, zoom));
                }
            }
        }
    }
    return cache.get(file);
}
Also used : ArrayList(java.util.ArrayList) DownloadRequest(net.osmand.map.MapTileDownloader.DownloadRequest) IIOException(javax.imageio.IIOException) Image(java.awt.Image) BufferedImage(java.awt.image.BufferedImage) File(java.io.File) Point(java.awt.Point)

Example 14 with IIOException

use of javax.imageio.IIOException in project tray by qzind.

the class PrintImage method parseData.

@Override
public void parseData(JSONArray printData, PrintOptions options) throws JSONException, UnsupportedOperationException {
    dpiScale = (options.getPixelOptions().getDensity() * options.getPixelOptions().getUnits().as1Inch()) / 72.0;
    for (int i = 0; i < printData.length(); i++) {
        JSONObject data = printData.getJSONObject(i);
        PrintingUtilities.Format format = PrintingUtilities.Format.valueOf(data.optString("format", "FILE").toUpperCase(Locale.ENGLISH));
        try {
            BufferedImage bi;
            if (format == PrintingUtilities.Format.BASE64) {
                bi = ImageIO.read(new ByteArrayInputStream(Base64.decode(data.getString("data"))));
            } else {
                bi = ImageIO.read(new URL(data.getString("data")));
            }
            images.add(bi);
        } catch (IIOException e) {
            if (e.getCause() != null && e.getCause() instanceof FileNotFoundException) {
                throw new UnsupportedOperationException("Image file specified could not be found.", e);
            } else {
                throw new UnsupportedOperationException(String.format("Cannot parse (%s)%s as an image", format, data.getString("data")), e);
            }
        } catch (IOException e) {
            throw new UnsupportedOperationException(String.format("Cannot parse (%s)%s as an image", format, data.getString("data")), e);
        }
    }
    log.debug("Parsed {} images for printing", images.size());
}
Also used : JSONObject(org.codehaus.jettison.json.JSONObject) ByteArrayInputStream(java.io.ByteArrayInputStream) FileNotFoundException(java.io.FileNotFoundException) IIOException(javax.imageio.IIOException) IIOException(javax.imageio.IIOException) IOException(java.io.IOException) PrintingUtilities(qz.utils.PrintingUtilities) BufferedImage(java.awt.image.BufferedImage) URL(java.net.URL)

Example 15 with IIOException

use of javax.imageio.IIOException in project UniversalMediaServer by UniversalMediaServer.

the class ImagesUtil method transcodeImage.

/**
 * Converts and scales an image in one operation. Scaling can be with or
 * without padding. Preserves aspect ratio and rotates/flips the image
 * according to Exif orientation. Format support is limited to that of
 * {@link ImageIO}. Only one of the three input arguments may be used in any
 * given call. Note that {@code outputProfile} overrides
 * {@code outputFormat}.
 * <p>
 * <b> This method consumes and closes {@code inputStream}. </b>
 *
 * @param inputByteArray the source image in a supported format.
 * @param inputImage the source {@link Image}.
 * @param inputStream the source image in a supported format.
 * @param width the new width or 0 to disable scaling.
 * @param height the new height or 0 to disable scaling.
 * @param scaleType the {@link ScaleType} to use when scaling.
 * @param outputFormat the {@link ImageFormat} to convert to or
 *            {@link ImageFormat#SOURCE} to preserve source format.
 *            Overridden by {@code outputProfile}.
 * @param outputProfile the {@link DLNAImageProfile} to convert to. This
 *            overrides {@code outputFormat}.
 * @param dlnaCompliant whether or not the output image should be restricted
 *            to DLNA compliance. This also means that the output can be
 *            safely cast to {@link DLNAImage}.
 * @param dlnaThumbnail whether or not the output image should be restricted
 *            to DLNA thumbnail compliance. This also means that the output
 *            can be safely cast to {@link DLNAThumbnail}.
 * @param padToSize whether padding should be used if source aspect doesn't
 *            match target aspect.
 * @return The scaled and/or converted image or {@code null} if the source
 *         is {@code null}.
 * @throws IOException if the operation fails.
 */
protected static Image transcodeImage(byte[] inputByteArray, Image inputImage, InputStream inputStream, int width, int height, ScaleType scaleType, ImageFormat outputFormat, DLNAImageProfile outputProfile, boolean dlnaCompliant, boolean dlnaThumbnail, boolean padToSize) throws IOException {
    if (inputByteArray == null && inputStream == null && inputImage == null) {
        return null;
    }
    if ((inputByteArray != null & inputImage != null) || (inputByteArray != null & inputStream != null) || (inputImage != null & inputStream != null)) {
        throw new IllegalArgumentException("Use either inputByteArray, inputImage or inputStream");
    }
    boolean trace = LOGGER.isTraceEnabled();
    if (trace) {
        StringBuilder sb = new StringBuilder();
        if (scaleType != null) {
            sb.append("ScaleType = ").append(scaleType);
        }
        if (width > 0 && height > 0) {
            if (sb.length() > 0) {
                sb.append(", ");
            }
            sb.append("Width = ").append(width).append(", Height = ").append(height);
        }
        if (sb.length() > 0) {
            sb.append(", ");
        }
        sb.append("PadToSize = ").append(padToSize ? "True" : "False");
        LOGGER.trace("Converting {} image source to {} format and type {} using the following parameters: {}", inputByteArray != null ? "byte array" : inputImage != null ? "Image" : "input stream", outputProfile != null ? outputProfile : outputFormat, dlnaThumbnail ? "DLNAThumbnail" : dlnaCompliant ? "DLNAImage" : "Image", sb);
    }
    ImageIO.setUseCache(false);
    dlnaCompliant = dlnaCompliant || dlnaThumbnail;
    if (inputImage != null) {
        inputByteArray = inputImage.getBytes(false);
    } else if (inputStream != null) {
        inputByteArray = ImagesUtil.toByteArray(inputStream);
    }
    // outputProfile overrides outputFormat
    if (outputProfile != null) {
        if (dlnaThumbnail && outputProfile.equals(DLNAImageProfile.GIF_LRG)) {
            outputProfile = DLNAImageProfile.JPEG_LRG;
        }
        // Default to correct ScaleType for the profile
        if (scaleType == null) {
            if (DLNAImageProfile.JPEG_RES_H_V.equals(outputProfile)) {
                scaleType = ScaleType.EXACT;
            } else {
                scaleType = ScaleType.MAX;
            }
        }
        outputFormat = ImageFormat.toImageFormat(outputProfile);
        width = width > 0 ? width : outputProfile.getMaxWidth();
        height = height > 0 ? height : outputProfile.getMaxHeight();
    } else if (scaleType == null) {
        scaleType = ScaleType.MAX;
    }
    ImageReaderResult inputResult;
    try {
        inputResult = ImageIOTools.read(new ByteArrayInputStream(inputByteArray));
    } catch (IIOException e) {
        throw new UnknownFormatException("Unable to read image format", e);
    }
    if (inputResult.bufferedImage == null || inputResult.imageFormat == null) {
        // ImageIO doesn't support the image format
        throw new UnknownFormatException("Failed to transform image because the source format is unknown");
    }
    if (outputFormat == null || outputFormat == ImageFormat.SOURCE) {
        outputFormat = inputResult.imageFormat;
    }
    BufferedImage bufferedImage = inputResult.bufferedImage;
    boolean reencode = false;
    if (outputProfile == null && dlnaCompliant) {
        // if the source image has alpha and JPEG if not.
        switch(outputFormat) {
            case GIF:
                if (dlnaThumbnail) {
                    outputFormat = ImageFormat.JPEG;
                }
                break;
            case JPEG:
            case PNG:
                break;
            default:
                if (bufferedImage.getColorModel().hasAlpha()) {
                    outputFormat = ImageFormat.PNG;
                } else {
                    outputFormat = ImageFormat.JPEG;
                }
        }
    }
    Metadata metadata = null;
    ExifOrientation orientation;
    if (inputImage != null && inputImage.getImageInfo() != null) {
        orientation = inputImage.getImageInfo().getExifOrientation();
    } else {
        try {
            metadata = getMetadata(inputByteArray, inputResult.imageFormat);
        } catch (IOException | ImageProcessingException e) {
            LOGGER.error("Failed to read input image metadata: {}", e.getMessage());
            LOGGER.trace("", e);
            metadata = new Metadata();
        }
        if (metadata == null) {
            metadata = new Metadata();
        }
        orientation = parseExifOrientation(metadata);
    }
    if (orientation != ExifOrientation.TOP_LEFT) {
        // Rotate the image before doing all the other checks
        BufferedImage oldBufferedImage = bufferedImage;
        bufferedImage = Thumbnails.of(bufferedImage).scale(1.0d).addFilter(ExifFilterUtils.getFilterForOrientation(orientation.getThumbnailatorOrientation())).asBufferedImage();
        oldBufferedImage.flush();
        // Re-parse the metadata after rotation as these are newly generated.
        ByteArrayOutputStream tmpOutputStream = new ByteArrayOutputStream(inputByteArray.length);
        Thumbnails.of(bufferedImage).scale(1.0d).outputFormat(outputFormat.toString()).toOutputStream(tmpOutputStream);
        try {
            metadata = getMetadata(tmpOutputStream.toByteArray(), outputFormat);
        } catch (IOException | ImageProcessingException e) {
            LOGGER.debug("Failed to read rotated image metadata: {}", e.getMessage());
            LOGGER.trace("", e);
            metadata = new Metadata();
        }
        if (metadata == null) {
            metadata = new Metadata();
        }
        reencode = true;
    }
    if (outputProfile == null && dlnaCompliant) {
        // Set a suitable output profile.
        if (width < 1 || height < 1) {
            outputProfile = DLNAImageProfile.getClosestDLNAProfile(bufferedImage.getWidth(), bufferedImage.getHeight(), outputFormat, true);
            width = outputProfile.getMaxWidth();
            height = outputProfile.getMaxHeight();
        } else {
            outputProfile = DLNAImageProfile.getClosestDLNAProfile(calculateScaledResolution(bufferedImage.getWidth(), bufferedImage.getHeight(), scaleType, width, height), outputFormat, true);
            width = Math.min(width, outputProfile.getMaxWidth());
            height = Math.min(height, outputProfile.getMaxHeight());
        }
        if (DLNAImageProfile.JPEG_RES_H_V.equals(outputProfile)) {
            scaleType = ScaleType.EXACT;
        }
    }
    boolean convertColors = bufferedImage.getType() == BufferedImageType.TYPE_CUSTOM.getTypeId() || bufferedImage.getType() == BufferedImageType.TYPE_BYTE_BINARY.getTypeId() || bufferedImage.getColorModel().getColorSpace().getType() != ColorSpaceType.TYPE_RGB.getTypeId();
    // Impose DLNA format restrictions
    if (!reencode && outputFormat == inputResult.imageFormat && outputProfile != null) {
        DLNAComplianceResult complianceResult;
        switch(outputFormat) {
            case GIF:
            case JPEG:
            case PNG:
                ImageInfo imageInfo;
                // metadata is only null at this stage if inputImage != null and no rotation was necessary
                if (metadata == null) {
                    imageInfo = inputImage.getImageInfo();
                }
                imageInfo = ImageInfo.create(bufferedImage.getWidth(), bufferedImage.getHeight(), inputResult.imageFormat, ImageInfo.SIZE_UNKNOWN, bufferedImage.getColorModel(), metadata, false, true);
                complianceResult = DLNAImageProfile.checkCompliance(imageInfo, outputProfile);
                break;
            default:
                throw new IllegalStateException("Unexpected image format: " + outputFormat);
        }
        reencode = reencode || convertColors || !complianceResult.isFormatCorrect() || !complianceResult.isColorsCorrect();
        ;
        if (!complianceResult.isResolutionCorrect()) {
            width = width > 0 && complianceResult.getMaxWidth() > 0 ? Math.min(width, complianceResult.getMaxWidth()) : width > 0 ? width : complianceResult.getMaxWidth();
            height = height > 0 && complianceResult.getMaxHeight() > 0 ? Math.min(height, complianceResult.getMaxHeight()) : height > 0 ? height : complianceResult.getMaxHeight();
        }
        if (trace) {
            if (complianceResult.isAllCorrect()) {
                LOGGER.trace("Image conversion DLNA compliance check: The source image is compliant");
            } else {
                LOGGER.trace("Image conversion DLNA compliance check for {}: " + "The source image colors are {}, format is {} and resolution ({} x {}) is {}.\nFailures:\n  {}", outputProfile, complianceResult.isColorsCorrect() ? "compliant" : "non-compliant", complianceResult.isFormatCorrect() ? "compliant" : "non-compliant", bufferedImage.getWidth(), bufferedImage.getHeight(), complianceResult.isResolutionCorrect() ? "compliant" : "non-compliant", StringUtils.join(complianceResult.getFailures(), "\n  "));
            }
        }
    }
    if (convertColors) {
        // Preserve alpha channel if the output format supports it
        BufferedImageType outputImageType;
        if ((outputFormat == ImageFormat.PNG || outputFormat == ImageFormat.PSD) && bufferedImage.getColorModel().getNumComponents() == 4) {
            outputImageType = bufferedImage.isAlphaPremultiplied() ? BufferedImageType.TYPE_4BYTE_ABGR_PRE : BufferedImageType.TYPE_4BYTE_ABGR;
        } else {
            outputImageType = BufferedImageType.TYPE_3BYTE_BGR;
        }
        BufferedImage convertedImage = new BufferedImage(bufferedImage.getWidth(), bufferedImage.getHeight(), outputImageType.getTypeId());
        ColorConvertOp colorConvertOp = new ColorConvertOp(null);
        colorConvertOp.filter(bufferedImage, convertedImage);
        bufferedImage.flush();
        bufferedImage = convertedImage;
        reencode = true;
    }
    if (width < 1 || height < 1 || (scaleType == ScaleType.MAX && bufferedImage.getWidth() <= width && bufferedImage.getHeight() <= height) || (scaleType == ScaleType.EXACT && bufferedImage.getWidth() == width && bufferedImage.getHeight() == height)) {
        // No resize, just convert
        if (!reencode && inputResult.imageFormat == outputFormat) {
            // Nothing to do, just return source
            // metadata is only null at this stage if inputImage != null
            Image result;
            if (dlnaThumbnail) {
                result = metadata == null ? new DLNAThumbnail(inputImage, outputProfile, false) : new DLNAThumbnail(inputByteArray, outputFormat, bufferedImage, metadata, outputProfile, false);
            } else if (dlnaCompliant) {
                result = metadata == null ? new DLNAImage(inputImage, outputProfile, false) : new DLNAImage(inputByteArray, outputFormat, bufferedImage, metadata, outputProfile, false);
            } else {
                result = metadata == null ? new Image(inputImage, false) : new Image(inputByteArray, outputFormat, bufferedImage, metadata, false);
            }
            bufferedImage.flush();
            if (trace) {
                LOGGER.trace("No conversion is needed, returning source image with width = {}, height = {} and output {}.", bufferedImage.getWidth(), bufferedImage.getHeight(), dlnaCompliant && outputProfile != null ? "profile: " + outputProfile : "format: " + outputFormat);
            }
            return result;
        } else if (!reencode) {
            // Convert format
            reencode = true;
        }
    } else {
        boolean force = DLNAImageProfile.JPEG_RES_H_V.equals(outputProfile);
        BufferedImage oldBufferedImage = bufferedImage;
        if (padToSize && force) {
            bufferedImage = Thumbnails.of(bufferedImage).forceSize(width, height).addFilter(new Canvas(width, height, Positions.CENTER, Color.BLACK)).asBufferedImage();
        } else if (padToSize) {
            bufferedImage = Thumbnails.of(bufferedImage).size(width, height).addFilter(new Canvas(width, height, Positions.CENTER, Color.BLACK)).asBufferedImage();
        } else if (force) {
            bufferedImage = Thumbnails.of(bufferedImage).forceSize(width, height).asBufferedImage();
        } else {
            bufferedImage = Thumbnails.of(bufferedImage).size(width, height).asBufferedImage();
        }
        oldBufferedImage.flush();
    }
    ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
    Thumbnails.of(bufferedImage).scale(1.0d).outputFormat(outputFormat.toString()).outputQuality(1.0f).toOutputStream(outputStream);
    byte[] outputByteArray = outputStream.toByteArray();
    Image result;
    if (dlnaThumbnail) {
        result = new DLNAThumbnail(outputByteArray, bufferedImage.getWidth(), bufferedImage.getHeight(), outputFormat, null, null, outputProfile, false);
    } else if (dlnaCompliant) {
        result = new DLNAImage(outputByteArray, bufferedImage.getWidth(), bufferedImage.getHeight(), outputFormat, null, null, outputProfile, false);
    } else {
        result = new Image(outputByteArray, bufferedImage.getWidth(), bufferedImage.getHeight(), outputFormat, null, null, true, false);
    }
    if (trace) {
        StringBuilder sb = new StringBuilder();
        sb.append("Convert colors = ").append(convertColors ? "True" : "False").append(", Re-encode = ").append(reencode ? "True" : "False");
        LOGGER.trace("Finished converting {} {} image{}. Output image resolution: {}, {}. Flags: {}", inputResult.width + "×" + inputResult.height, inputResult.imageFormat, orientation != ExifOrientation.TOP_LEFT ? " with orientation " + orientation : "", bufferedImage.getWidth() + "×" + bufferedImage.getHeight(), dlnaCompliant && outputProfile != null ? "profile: " + outputProfile : "format: " + outputFormat, sb);
    }
    bufferedImage.flush();
    return result;
}
Also used : ImageProcessingException(com.drew.imaging.ImageProcessingException) BufferedImageType(net.pms.util.BufferedImageType) ImageReaderResult(net.pms.image.ImageIOTools.ImageReaderResult) Canvas(net.coobird.thumbnailator.filters.Canvas) Metadata(com.drew.metadata.Metadata) IIOException(javax.imageio.IIOException) IIOException(javax.imageio.IIOException) BufferedImage(java.awt.image.BufferedImage) DLNAImage(net.pms.dlna.DLNAImage) BufferedImage(java.awt.image.BufferedImage) DLNAThumbnail(net.pms.dlna.DLNAThumbnail) DLNAImage(net.pms.dlna.DLNAImage) ColorConvertOp(java.awt.image.ColorConvertOp) UnknownFormatException(net.pms.util.UnknownFormatException) DLNAComplianceResult(net.pms.dlna.DLNAImageProfile.DLNAComplianceResult)

Aggregations

IIOException (javax.imageio.IIOException)60 Point (java.awt.Point)23 IOException (java.io.IOException)23 BufferedImage (java.awt.image.BufferedImage)12 Rectangle (java.awt.Rectangle)11 IndexColorModel (java.awt.image.IndexColorModel)7 SampleModel (java.awt.image.SampleModel)7 WritableRaster (java.awt.image.WritableRaster)7 Iterator (java.util.Iterator)7 ColorModel (java.awt.image.ColorModel)6 ArrayList (java.util.ArrayList)6 ImageTypeSpecifier (javax.imageio.ImageTypeSpecifier)6 ImageInputStream (javax.imageio.stream.ImageInputStream)6 TIFFField (it.geosolutions.imageio.plugins.tiff.TIFFField)5 ColorSpace (java.awt.color.ColorSpace)5 ComponentSampleModel (java.awt.image.ComponentSampleModel)5 DataBufferByte (java.awt.image.DataBufferByte)5 ImageReader (javax.imageio.ImageReader)5 IIOMetadata (javax.imageio.metadata.IIOMetadata)5 ICC_ColorSpace (java.awt.color.ICC_ColorSpace)4