Search in sources :

Example 1 with WriteCompression

use of it.geosolutions.imageio.plugins.nitronitf.NITFUtilities.WriteCompression in project imageio-ext by geosolutions-it.

the class WriterTest method testNITFWrite.

@Test
@Ignore
public /**
 * Simple writing code which won't be run. You can use it as a sample on how to
 * setup some writing machinery.
 *
 * @throws IOException
 * @throws NITFException
 */
void testNITFWrite() throws IOException, NITFException {
    // This TEST won't run, you can use it as a sample on how to setup some writing code
    if (!NITFUtilities.isNITFAvailable()) {
        System.out.println("NITF native libs aren't available: skipping tests");
        return;
    }
    final String[] inputFilePaths = new String[] { "/tmp/sampleForNitf.tif" };
    final String[] requestedCrs = new String[] { "EPSG:32638" };
    FileImageInputStream fisi = new FileImageInputStream(new File("/tmp/license.txt"));
    int length = (int) fisi.length();
    byte[] data = new byte[length];
    fisi.read(data);
    // final int j = 0;
    // String inputFilePath = inputFilePaths[0];
    // 
    // final GeoTiffReader gtReader = new GeoTiffReader(new File(inputFilePath));
    // final GridCoverage2D gridCoverage = gtReader.read(null);
    // final RenderedImage ri = gridCoverage.getRenderedImage();
    // Image to be written
    RenderedImage ri = null;
    final int numBands = ri.getSampleModel().getNumBands();
    // Geometry geom = null;
    // ShapeFileWrapper shpWrapper = buildShape(geom);
    LinkedHashMap<String, Map<String, String>> tresMap = new LinkedHashMap<String, Map<String, String>>();
    // //
    // 
    // Populating TaggedRecordExtensions field with "FAKE" values,
    // for testing purposes
    // 
    // //
    NITFImageWriterSpi SPI = new NITFImageWriterSpi();
    final WriteCompression[] compressions = new WriteCompression[] { WriteCompression.NPJE_NL, WriteCompression.EPJE_NL, WriteCompression.NPJE_VL, WriteCompression.EPJE_VL };
    for (int w = 0; w < 4; w++) {
        final NITFImageWriter writer = new NITFImageWriter(SPI);
        final WriteCompression compression = compressions[w];
        String fileName = "/tmp/output_" + (numBands == 1 ? "PAN_" : "MULTI_") + compression.toString() + "_jp2.ntf";
        File nitfFile = new File(fileName);
        HeaderWrapper header = setupDefaultHeaderWrapper();
        Calendar cal = Calendar.getInstance();
        String timeStamp = null;
        synchronized (SDF) {
            // not thread safe
            timeStamp = SDF.format(cal.getTime());
        }
        header.setDateTime(timeStamp);
        List<TextWrapper> texts = new LinkedList<TextWrapper>();
        // Adding 3 text segments
        for (int i = 0; i < 3; i++) {
            TextWrapper text = setupDefaultNITFText();
            if (i > 0) {
                text.setTitle("SAMPLE" + i);
                text.setId("ID" + i);
            }
            text.setTextContent(data);
            texts.add(text);
        }
        header.setTitle(nitfFile.getName());
        NITFImageWriteParam param = new NITFImageWriteParam();
        NITFProperties metadata = new NITFProperties();
        param.setWriteCompression(compression);
        writer.setOutput(nitfFile);
        ImageWrapper image = new ImageWrapper();
        image.setImage(ri);
        image.setSource(DEFAULT_IMAGE_SOURCE);
        image.setTitle(numBands == 1 ? "SamplePanchromaticImagery.ntf" : "SampleMultiSpectralImagery.NTF");
        image.setId(numBands == 1 ? "P100000000" : "M100000000");
        List<String> comments = new ArrayList<String>(5);
        comments.add("The imagery and metadata data has been added ");
        comments.add("for testing purposes");
        comments.add("This is a test comment");
        comments.add("made of 5 lines");
        comments.add("of text.");
        image.setComments(comments);
        image.setCompression(compression);
        image.setDateTime(timeStamp);
        image.setImageCoordinateSystem("G");
        image.setIgeolo("453131173651215453133773651210453133713650902453131113650907");
        image.setImageMagnification("1.0");
        final int nBands = ri.getSampleModel().getNumBands();
        image.setImageCategory(nBands > 1 ? Category.MS : Category.VIS);
        Representation r = nBands > 1 ? Representation.RGB : Representation.MONO;
        String rString = r.toString();
        image.setRepresentation(r);
        ImageBand[] imageBands = new ImageBand[nBands];
        if (nBands == 1) {
            imageBands[0] = new ImageBand("", "" + rString.charAt(0));
        } else {
            for (int i = 0; i < nBands; i++) {
                imageBands[i] = new ImageBand("" + (rString.charAt(i)), "" + (rString.charAt(i)));
            }
        }
        image.setBands(imageBands);
        List<ImageWrapper> imagesWrapper = new ArrayList<ImageWrapper>();
        imagesWrapper.add(image);
        metadata.setHeader(header);
        // metadata.setShape(shpWrapper);
        image.setTres(tresMap);
        metadata.setImagesWrapper(imagesWrapper);
        metadata.setTextsWrapper(texts);
        param.setNitfProperties(metadata);
        writer.write(null, new IIOImage(ri, null, null), param);
        writer.dispose();
    // gtReader.dispose();
    }
}
Also used : ImageBand(it.geosolutions.imageio.plugins.nitronitf.wrapper.ImageWrapper.ImageBand) ArrayList(java.util.ArrayList) LinkedHashMap(java.util.LinkedHashMap) IIOImage(javax.imageio.IIOImage) ImageWrapper(it.geosolutions.imageio.plugins.nitronitf.wrapper.ImageWrapper) WriteCompression(it.geosolutions.imageio.plugins.nitronitf.NITFUtilities.WriteCompression) NITFProperties(it.geosolutions.imageio.plugins.nitronitf.wrapper.NITFProperties) Calendar(java.util.Calendar) NITFImageWriterSpi(it.geosolutions.imageio.plugins.nitronitf.NITFImageWriterSpi) Representation(it.geosolutions.imageio.plugins.nitronitf.wrapper.ImageWrapper.Representation) LinkedList(java.util.LinkedList) FileImageInputStream(javax.imageio.stream.FileImageInputStream) NITFImageWriter(it.geosolutions.imageio.plugins.nitronitf.NITFImageWriter) TextWrapper(it.geosolutions.imageio.plugins.nitronitf.wrapper.TextWrapper) NITFImageWriteParam(it.geosolutions.imageio.plugins.nitronitf.NITFImageWriteParam) HeaderWrapper(it.geosolutions.imageio.plugins.nitronitf.wrapper.HeaderWrapper) RenderedImage(java.awt.image.RenderedImage) File(java.io.File) LinkedHashMap(java.util.LinkedHashMap) Map(java.util.Map) Ignore(org.junit.Ignore) Test(org.junit.Test)

Example 2 with WriteCompression

use of it.geosolutions.imageio.plugins.nitronitf.NITFUtilities.WriteCompression in project imageio-ext by geosolutions-it.

the class NITFImageWriter method writeNITF.

/**
 * Do the real write operation (writing images, texts, ...)
 *
 * @param record
 * @param images
 * @param shp
 * @param fis
 * @param text
 * @return
 * @throws NITFException
 * @throws IOException
 */
private boolean writeNITF(final Record record, final List<ImageWrapper> images, final ShapeFileWrapper shp, final FileImageInputStreamExt fis, final List<TextWrapper> texts) throws NITFException, IOException {
    final int numImages = images.size();
    ImageWrapper image = images.get(0);
    RenderedImage ri = image.getImage();
    WriteCompression compression = image.getCompression();
    int nBands = ri.getSampleModel().getNumBands();
    boolean written = false;
    Writer writer = new Writer();
    IOHandle handle = new IOHandle(outputFile.getCanonicalPath(), IOHandle.NITF_ACCESS_WRITEONLY, IOHandle.NITF_CREATE);
    byte[] shapeFileData = null;
    final boolean isJP2 = !(compression == WriteCompression.UNCOMPRESSED);
    if (shp != null) {
        shapeFileData = getShapeData(record, shp);
    }
    boolean prepared = false;
    if (isJP2) {
        // //
        // 
        // get the JP2 Codestream previously written with Kakadu and transfer its content within
        // the NITF imageSegment
        // 
        // //
        WriteHandler codeStream = null;
        IOInterface io;
        final int size = (int) fis.length();
        io = new IOFileInputStream(fis);
        writer.prepare(record, handle);
        if (shapeFileData != null) {
            writeData(shapeFileData, writer);
        }
        codeStream = new StreamIOWriteHandler(io, 0, size);
        writer.setImageWriteHandler(0, codeStream);
        prepared = true;
    }
    if (!isJP2 || numImages > 1) {
        if (!prepared) {
            writer.prepare(record, handle);
        }
        if (numImages == 1) {
            // setup a Writer
            if (shapeFileData != null) {
                writeData(shapeFileData, writer);
            }
            ImageSource imageSource = new ImageSource();
            nitf.ImageWriter imageWriter = writer.getNewImageWriter(0);
            boolean[] successes = new boolean[nBands];
            final boolean isMono = images.get(0).getImage().getSampleModel().getNumBands() == 1;
            if (isMono) {
                DataBufferByte dbb = (DataBufferByte) ri.getData().getDataBuffer();
                BandSource bs = new MemorySource(dbb.getData(), dbb.getSize(), 0, 0, 0);
                successes[0] = imageSource.addBand(bs);
            } else {
                for (int i = 0; i < nBands; i++) {
                    RenderedImage band = BandSelectDescriptor.create(ri, new int[] { i }, null);
                    DataBufferByte dbb = (DataBufferByte) band.getData().getDataBuffer();
                    BandSource bs = new MemorySource(dbb.getData(), dbb.getSize(), 0, 0, 0);
                    successes[i] = imageSource.addBand(bs);
                }
            }
            imageWriter.attachSource(imageSource);
        } else {
            ImageWrapper img = images.get(1);
            ri = img.getImage();
            nBands = ri.getSampleModel().getNumBands();
            ImageSource imageSource = new ImageSource();
            nitf.ImageWriter imageWriter2 = writer.getNewImageWriter(1);
            boolean[] successes = new boolean[nBands];
            DataBufferByte dbb = (DataBufferByte) ri.getData().getDataBuffer();
            BandSource bs = new MemorySource(dbb.getData(), dbb.getSize(), 0, 0, 0);
            successes[0] = imageSource.addBand(bs);
            imageWriter2.attachSource(imageSource);
        }
    }
    // Adding text
    if (texts != null && !texts.isEmpty()) {
        int i = 0;
        for (TextWrapper text : texts) {
            byte[] textContent = text.getTextContent();
            if (textContent != null) {
                SegmentWriter textWriter = writer.getNewTextWriter(i++);
                SegmentSource source = SegmentSource.makeSegmentMemorySource(textContent, textContent.length, 0, 0);
                textWriter.attachSource(source);
            }
        }
    }
    written = writer.write();
    if (handle != null) {
        handle.close();
    }
    return written;
}
Also used : IOHandle(nitf.IOHandle) StreamIOWriteHandler(nitf.StreamIOWriteHandler) DataBufferByte(java.awt.image.DataBufferByte) SegmentSource(nitf.SegmentSource) BandSource(nitf.BandSource) TextWrapper(it.geosolutions.imageio.plugins.nitronitf.wrapper.TextWrapper) ImageWrapper(it.geosolutions.imageio.plugins.nitronitf.wrapper.ImageWrapper) WriteHandler(nitf.WriteHandler) StreamIOWriteHandler(nitf.StreamIOWriteHandler) IOInterface(nitf.IOInterface) ImageSource(nitf.ImageSource) MemorySource(nitf.MemorySource) RenderedImage(java.awt.image.RenderedImage) SegmentWriter(nitf.SegmentWriter) JP2KKakaduImageWriter(it.geosolutions.imageio.plugins.jp2k.JP2KKakaduImageWriter) SegmentWriter(nitf.SegmentWriter) Writer(nitf.Writer) ImageWriter(javax.imageio.ImageWriter) WriteCompression(it.geosolutions.imageio.plugins.nitronitf.NITFUtilities.WriteCompression)

Example 3 with WriteCompression

use of it.geosolutions.imageio.plugins.nitronitf.NITFUtilities.WriteCompression in project imageio-ext by geosolutions-it.

the class NITFImageWriter method addImageSegment.

/**
 * Setup the ImageSegment
 *
 * @param record
 * @param images
 * @param fis
 * @param compression
 * @return
 * @throws NITFException
 * @throws IOException
 */
private static void addImageSegment(final Record record, final List<ImageWrapper> images, final FileImageInputStreamExt fis, final WriteCompression compression) throws NITFException, IOException {
    ImageSegment segment = null;
    ImageSubheader subheader = null;
    int img = 0;
    // Using a loop for future usage of the cloudCover image
    for (ImageWrapper image : images) {
        // Getting compression parameter and imageProperties
        WriteCompression writeCompression = img == 0 ? compression : WriteCompression.UNCOMPRESSED;
        segment = record.newImageSegment();
        // Setting up the image Sub Header
        subheader = segment.getSubheader();
        double bpppb = initImageSubHeader(image, subheader, writeCompression, fis);
        if (img == 0) {
            initTREs(subheader, image, writeCompression, bpppb);
        }
        img++;
    }
}
Also used : ImageSegment(nitf.ImageSegment) ImageSubheader(nitf.ImageSubheader) ImageWrapper(it.geosolutions.imageio.plugins.nitronitf.wrapper.ImageWrapper) WriteCompression(it.geosolutions.imageio.plugins.nitronitf.NITFUtilities.WriteCompression)

Example 4 with WriteCompression

use of it.geosolutions.imageio.plugins.nitronitf.NITFUtilities.WriteCompression in project imageio-ext by geosolutions-it.

the class NITFImageWriter method write.

@Override
public void write(IIOMetadata streamMetadata, IIOImage image, ImageWriteParam param) throws IOException {
    // Headers and segments initialization
    NITFImageWriteParam nitfParam = null;
    HeaderWrapper header = null;
    Map<String, Map<String, String>> extensionsMap = null;
    ShapeFileWrapper shape = null;
    List<TextWrapper> texts = null;
    WriteCompression compression = null;
    List<ImageWrapper> inputImages = null;
    if (param != null && param instanceof NITFImageWriteParam) {
        nitfParam = (NITFImageWriteParam) param;
        NITFProperties nitfMetadata = nitfParam.getNitfProperties();
        if (nitfMetadata != null) {
            header = nitfMetadata.getHeader();
            shape = nitfMetadata.getShape();
            texts = nitfMetadata.getTextsWrapper();
            inputImages = nitfMetadata.getImagesWrapper();
        }
        compression = nitfParam.getWriteCompression();
    }
    ImageWrapper imageW = inputImages.get(0);
    RenderedImage ri = imageW.getImage();
    final boolean isJP2 = (compression != null && compression != WriteCompression.UNCOMPRESSED);
    FileImageInputStreamExt jp2Stream = null;
    File tempFile = null;
    try {
        Record record = new Record(Version.NITF_21);
        if (isJP2) {
            // Proceeding with jp2 compression
            if (JP2_TEMP_FOLDER != null) {
                tempFile = File.createTempFile("jp2compressed", ".jpc", new File(JP2_TEMP_FOLDER));
            }
            String parentPath = outputFile.getParent();
            String name = FilenameUtils.getBaseName(outputFile.getCanonicalPath());
            tempFile = new File(parentPath + File.separatorChar + name + ".j2c");
            prepareJP2Image(ri, tempFile, compression);
            jp2Stream = new FileImageInputStreamExtImpl(tempFile);
        }
        // populating the file header
        initFileHeader(record, header);
        // adding an image segment to the record
        addImageSegment(record, inputImages, jp2Stream, compression);
        if (texts != null && !texts.isEmpty()) {
            // adding a text segment if present
            addTextSegment(record, texts);
        }
        if (!writeNITF(record, inputImages, shape, jp2Stream, texts)) {
            throw new IOException("Unable to successfully write");
        }
    } catch (Throwable t) {
        IOException ioe = new IOException();
        ioe.initCause(t);
        throw ioe;
    } finally {
        // Releasing resources
        if (jp2Stream != null) {
            try {
                jp2Stream.close();
            } catch (Throwable thr) {
            // Eat exception
            }
        }
        if (tempFile != null) {
            try {
                tempFile.delete();
            } catch (Throwable thr) {
            }
        }
    }
    // record.destruct();
    if (LOGGER.isLoggable(Level.FINE)) {
        LOGGER.log(Level.FINE, "Successfully wrote NITF: " + outputFile);
    }
}
Also used : NITFProperties(it.geosolutions.imageio.plugins.nitronitf.wrapper.NITFProperties) ShapeFileWrapper(it.geosolutions.imageio.plugins.nitronitf.wrapper.ShapeFileWrapper) IOException(java.io.IOException) TextWrapper(it.geosolutions.imageio.plugins.nitronitf.wrapper.TextWrapper) ImageWrapper(it.geosolutions.imageio.plugins.nitronitf.wrapper.ImageWrapper) FileImageInputStreamExt(it.geosolutions.imageio.stream.input.FileImageInputStreamExt) HeaderWrapper(it.geosolutions.imageio.plugins.nitronitf.wrapper.HeaderWrapper) Record(nitf.Record) FileImageInputStreamExtImpl(it.geosolutions.imageio.stream.input.FileImageInputStreamExtImpl) RenderedImage(java.awt.image.RenderedImage) Map(java.util.Map) LinkedHashMap(java.util.LinkedHashMap) File(java.io.File) WriteCompression(it.geosolutions.imageio.plugins.nitronitf.NITFUtilities.WriteCompression)

Aggregations

WriteCompression (it.geosolutions.imageio.plugins.nitronitf.NITFUtilities.WriteCompression)4 ImageWrapper (it.geosolutions.imageio.plugins.nitronitf.wrapper.ImageWrapper)4 TextWrapper (it.geosolutions.imageio.plugins.nitronitf.wrapper.TextWrapper)3 RenderedImage (java.awt.image.RenderedImage)3 HeaderWrapper (it.geosolutions.imageio.plugins.nitronitf.wrapper.HeaderWrapper)2 NITFProperties (it.geosolutions.imageio.plugins.nitronitf.wrapper.NITFProperties)2 File (java.io.File)2 LinkedHashMap (java.util.LinkedHashMap)2 Map (java.util.Map)2 JP2KKakaduImageWriter (it.geosolutions.imageio.plugins.jp2k.JP2KKakaduImageWriter)1 NITFImageWriteParam (it.geosolutions.imageio.plugins.nitronitf.NITFImageWriteParam)1 NITFImageWriter (it.geosolutions.imageio.plugins.nitronitf.NITFImageWriter)1 NITFImageWriterSpi (it.geosolutions.imageio.plugins.nitronitf.NITFImageWriterSpi)1 ImageBand (it.geosolutions.imageio.plugins.nitronitf.wrapper.ImageWrapper.ImageBand)1 Representation (it.geosolutions.imageio.plugins.nitronitf.wrapper.ImageWrapper.Representation)1 ShapeFileWrapper (it.geosolutions.imageio.plugins.nitronitf.wrapper.ShapeFileWrapper)1 FileImageInputStreamExt (it.geosolutions.imageio.stream.input.FileImageInputStreamExt)1 FileImageInputStreamExtImpl (it.geosolutions.imageio.stream.input.FileImageInputStreamExtImpl)1 DataBufferByte (java.awt.image.DataBufferByte)1 IOException (java.io.IOException)1