当前位置: 首页 > 面试题库 >

用于KML(JAK)将图像嵌入kmz文件中的Java API

严远
2023-03-14
问题内容

有没有一种方法可以使用Java API for
KML(JAK)将图像文件添加到kmz文件中?我可以毫无问题地创建一个kml文件,但是我试图嵌入资源(例如带有一些图像文件的images文件夹),但是marshalAsKmz方法仅将Kml对象作为附加文件,因此我无法确定了解如何仅添加额外的图像。


问题答案:

我在一个项目上使用JAK已有一年多了。我用它来创建KML,然后将其编组为普通的KML(而不是KMZ)。我创建了一个单独的实用程序类,该实用程序类使用Java
SE“
Zip”类手动创建KMZ。它工作正常。KMZ只不过是一个.zip存档,其中仅包含一个.kml文件和0个或多个资源文件(例如图像等)。唯一的区别是,在输出文件时,将其命名为.kmz而不是.zip。在KML文档<Style>定义中,请使用与KML文档本身有关的路径来引用您的资源文件。KML文件被认为位于KMZ归档文件的“根目录”中。如果您的资源文件也位于KMZ(.zip)的根目录中,则您不需要路径,只需文件名。

编辑: 我实际上忘记Kml了在压缩文件之前删除了将JAK
对象编组到文件的中间步骤。我下面的实用程序方法会将Kml对象直接封送到ZipOutputStream

这是我创建的实用程序类,用于执行我所描述的事情。我将其发布在这里,希望其他人发布仅使用JAK的替代解决方案,以便将来我可以停用此代码。目前,这将为您完成工作。

注意:如果不使用slf4j,Apache Commons Lang或Commons I /
O,则只需对代码进行一些调整即可用您自己的代码删除/替换这些位。 显然,此代码需要JAK库。

package com.jimtough;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Collections;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

import org.apache.commons.io.IOUtils;
import org.apache.commons.lang.Validate;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import de.micromata.opengis.kml.v_2_2_0.Kml;

/**
 * Uses the classes in java.util.zip to package a KML file and its
 * supplementary files as a ZIP-compressed KMZ file.
 * 
 * @author JTOUGH
 */
public final class KMZPackager {

    private final static Logger logger =
        LoggerFactory.getLogger(KMZPackager.class);

    /**
     * Container for data that represents a single entry that will be added
     * to a compressed archive.
     * @author JTOUGH
     */
    public static abstract class DataSource {
        protected String archivedFileName;

        /**
         * Write the contents of this data source to the supplied
         * zip output stream.
         * 
         * @param zipOutputStream
         * @throws IOException
         */
        public abstract void writeToStream(ZipOutputStream zipOutputStream) 
            throws IOException; 
    }

    /**
     * Container for data that represents a single file that will be added
     * to a compressed archive.
     * @author JTOUGH
     */
    public static final class FileDataSource extends DataSource {
        private File sourceFile;

        /**
         * Constructor
         * 
         * @param sourceFile Actual file that will be added to the 
         *  compressed archive. 
         * @param archivedFileName Name that will be assigned to the compressed
         *  file within the archive. Caller must ensure that this value is
         *  unique within the archive otherwise an exception will be thrown
         *  when a name clash occurs during creation of the archive.
         *  This string must be non-null and non-empty. Any forward-slash
         *  characters in the string will be treated as directory separators
         *  when the KMZ/ZIP archive is created.
         * @throws IllegalArgumentException If either of these parameters
         *  is a null reference
         */
        public FileDataSource(
                File sourceFile,
                String archivedFileName) 
                throws IllegalArgumentException {
            Validate.notNull(sourceFile);
            Validate.notEmpty(archivedFileName);
            this.sourceFile = sourceFile;
            this.archivedFileName = archivedFileName;
        }

        @Override
        public void writeToStream(ZipOutputStream zipOutputStream)
                throws IOException {
            Validate.notNull(zipOutputStream);

            // Check that the file exists, and throw an appropriate exception
            // before reading it
            if (!sourceFile.exists()) {
                throw new IllegalArgumentException(
                    "File referenced in parameter [" +
                    sourceFile.getAbsolutePath() + "] does not exist");
            }

            FileInputStream fis = new FileInputStream(sourceFile);

            if (logger.isDebugEnabled()) {
                logger.debug("Adding file to KMZ archive" +
                    " | archive name: " + archivedFileName +
                    " | original name: " + 
                    sourceFile.getCanonicalPath());
            }

            // Mark the start of this new file in the ZIP stream
            ZipEntry entry = new ZipEntry(archivedFileName);
            zipOutputStream.putNextEntry(entry);

            // Use the Apache commons-io library to do a buffered
            // stream-to-stream copy
            try {
                IOUtils.copy(fis, zipOutputStream);
            } finally {
                fis.close();
            }
        }
    }

    /**
     * Container for a single JAK Kml object that will be marshalled
     * directly to a compressed KMZ archive as it is created
     * @author JTOUGH
     */
    public static final class KMLDataSource extends DataSource {
        private Kml kml;

        /**
         * Constructor
         * 
         * @param kml JAK Kml object that will be marshalled directly to the 
         *  compressed archive. 
         * @param archivedFileName Name that will be assigned to the compressed
         *  file within the archive. Caller must ensure that this value is
         *  unique within the archive otherwise an exception will be thrown
         *  when a name clash occurs during creation of the archive.
         *  This string must be non-null and non-empty. Any forward-slash
         *  characters in the string will be treated as directory separators
         *  when the KMZ/ZIP archive is created.
         * @throws IllegalArgumentException If either of these parameters
         *  is a null reference
         */
        public KMLDataSource(
                Kml kml,
                String archivedFileName) 
                throws IllegalArgumentException {
            Validate.notNull(kml);
            Validate.notEmpty(archivedFileName);
            this.kml = kml;
            this.archivedFileName = archivedFileName;
        }

        @Override
        public void writeToStream(ZipOutputStream zipOutputStream) throws IOException {
            Validate.notNull(zipOutputStream);
            // Mark the start of this new file in the ZIP stream
            ZipEntry entry = new ZipEntry(archivedFileName);
            zipOutputStream.putNextEntry(entry);

            // Marshal the Kml object directly to the ZipOutputStream
            if (logger.isDebugEnabled()) {
                logger.debug("Marshalling KML to KMZ archive" +
                    " | archive name: " + archivedFileName);
            }
            kml.marshal(zipOutputStream);   
        }
    }

    /**
     * Container for a stream holding a Kml document. This will be written
     * directly to a compressed KMZ archive as it is created.
     */
    public static final class StreamDataSource extends DataSource {

        private InputStream inputStream;

        /**
         * Constructor
         * 
         * @param inputStream the inputStream holding the KML text
         * @param archivedFileName Name that will be assigned to the compressed
         *  file within the archive. Caller must ensure that this value is
         *  unique within the archive otherwise an exception will be thrown
         *  when a name clash occurs during creation of the archive.
         *  This string must be non-null and non-empty. Any forward-slash
         *  characters in the string will be treated as directory separators
         *  when the KMZ/ZIP archive is created.
         * @throws IllegalArgumentException If either of these parameters
         *  is a null reference
         */
        public StreamDataSource(
                InputStream inputStream,
                String archivedFileName) 
                throws IllegalArgumentException {
            Validate.notNull(inputStream);
            Validate.notEmpty(archivedFileName);
            this.inputStream = inputStream;
            this.archivedFileName = archivedFileName;
        }

        @Override
        public void writeToStream(ZipOutputStream zipOutputStream) throws IOException {
            Validate.notNull(zipOutputStream);
            // Mark the start of this new file in the ZIP stream
            ZipEntry entry = new ZipEntry(archivedFileName);
            zipOutputStream.putNextEntry(entry);

            // Use the Apache commons-io library to do a buffered
            // stream-to-stream copy
            if (logger.isDebugEnabled()) {
                logger.debug("Copying KML from stream to KMZ archive" +
                    " | archive name: " + archivedFileName);
            }
            try {
                IOUtils.copy(inputStream, zipOutputStream);
            } finally {
                inputStream.close();
            }
        }
    }

    /**
     * Use ZIP compression to package a KML file and its supplementary files
     * as a KMZ archive.  The compressed archive will be written to the 
     * supplied output stream.
     * 
     * @param os OutputStream to which the compressed archive will be written.
     *  This parameter must be a non-null reference to an OutputStream that
     *  is open for write operations.
     * @param kmlDataSource KML to be added to the compressed archive. 
     *  This parameter must not be null. The archivedFileName attribute must
     *  end with the .kml extension. The file is added to the compressed 
     *  archive. The KMZ specification states that a KMZ archive must only
     *  contain a single KML file.
     * @param supplementaryFileList List of file locations for supplementary
     *  files that will be included in the KMZ archive. A common example
     *  would be icons or image overlays that are referenced in the KML file.
     *  This parameter can be null or an empty list if there are no 
     *  supplementary files to include in the KMZ. Each source that is included
     *  in the list must refer to an existing file that does NOT have the
     *  file extension '.kml'.
     * @throws RuntimeException Thrown if anything unexpected occurs
     *  that prevents execution from continuing or if any of the stated
     *  conditions for the input parameters are violated
     */
    public void packageAsKMZ(
            OutputStream os,
            DataSource kmlDataSource,
            List<FileDataSource> supplementaryFileList) 
            throws RuntimeException {
        ZipOutputStream zipOutputStream = null;
        boolean isExceptionThrown = false;
        Exception caughtException = null;
        List<FileDataSource> supplFileList = supplementaryFileList;

        try {
            Validate.notNull(os, "os parameter cannot be null");
            Validate.notNull(kmlDataSource, 
                "kmlFileDataSource parameter cannot be null");

            // Treat a null parameter just like an empty list (which is OK)
            if (supplFileList == null) {
                supplFileList = Collections.emptyList();
            }

            if (logger.isDebugEnabled()) {
                logger.debug(
                    "Creating KMZ archive" +
                    " | supplementary files: " + supplFileList.size());
            }

            // Create a buffered output stream for the new KMZ file
            zipOutputStream = new ZipOutputStream(new BufferedOutputStream(os));
            Validate.isTrue(
                kmlDataSource.archivedFileName.endsWith(".kml"),
                "KML archived file name must end with .kml");
            kmlDataSource.writeToStream(zipOutputStream);

            // Now process the list of supplementary files
            if (logger.isDebugEnabled()) {
                logger.debug("Adding supplementary files to KMZ archive" +
                    " | archive name: ");
            }
            for (FileDataSource ds : supplFileList) {
                Validate.isTrue(
                    !ds.archivedFileName.endsWith(".kml"),
                    "Not legal to include .kml files in supplementary list");
                ds.writeToStream(zipOutputStream);
            }

            // Close the output stream to complete the ZIP creation
            zipOutputStream.flush();
            zipOutputStream.close();

            logger.info("KMZ archive created successfully");

        } catch (IOException e) {
            isExceptionThrown = true;
            caughtException = e;
            logger.error("IOException while creating ZIP stream");
        } catch (IllegalArgumentException e) {
            isExceptionThrown = true;
            caughtException = e;
        } catch (RuntimeException e) {
            isExceptionThrown = true;
            caughtException = e;
        } finally {
            if (isExceptionThrown) {
                try {
                    if (zipOutputStream != null) {
                        zipOutputStream.close();
                    }
                } catch (IOException ioe) {
                    // Don't care
                }
                throw new RuntimeException(caughtException);
            }
        }
    }
}


 类似资料:
  • 我目前正在使用JAK(KML的Java API)与Google Earth和定制的KML文件进行交互。我可以使用placemark p.getName()或point等工具获取/设置地名的名称、描述和坐标。getCoordinates();但我遇到的问题是获取图标所用图像的url。例如,如果我的kml文件中有这个placemark(包含在文档中,然后是整个kml标记): 我怎样才能抓住那个png

  • 有没有办法删除KML文件中额外的命名空间前缀(即ns2)? 这是我从代码中收到的 kml 的一个示例: 我想要的是这样的: 这是我的java代码: 非常感谢任何帮助!谢谢!

  • 问题内容: 我知道可以在Tkinter文本小部件中嵌入图像,但是我一直无法找到一些简单的示例代码。具体来说,我需要嵌入jpg,因此根据文档,我认为我需要使用photoimage类 我试图用这个: 其中imgfn是图像文件名,而text是我的文本窗口小部件,但是我得到“ _tkinter.TclError:无法识别图像文件中的数据……” 谢谢你的帮助! 问题答案: 仅处理和文件。为了与Tkinter

  • 在花了3天时间无法解决这个问题后,我正在编辑我的问题:我有一个西雅图所有楼梯的网站,当点击标记时,它会显示描述和图像。它已经运行了几年。(http://seattlestairs.home.comcast.net/~seattlestairs) 然后谷歌改变了他们kml文件的格式,如果我用新的kml替换旧的,我就看不到图像了。您可以在以下位置看到:(http://seattlestairs.hom

  • 问题内容: 我正在尝试发送包含嵌入式gif图像的多部分/相关html电子邮件。该电子邮件是使用Oracle PL / SQL生成的。我的尝试失败了,图片显示为红色X(在Outlook 2007和yahoo邮件中) 我已经发送HTML电子邮件已有一段时间了,但是我现在的要求是在电子邮件中使用多个gif图像。我可以将它们存储在我们的一台Web服务器上并仅链接到它们,但是许多用户的电子邮件客户端不会自动

  • 我有一个shapefile,我正在尝试将其转换为kml文件,以便在Qlik意义上使用它。我想将kml区域和kml名称(标记为扇区ID)存储在kml中。下面是我使用的代码 我试过各种各样的软件包,但似乎都不管用。到目前为止,我只能得到没有正确标签(扇区ID)的kml区域。我尝试过的方法之一是plotKML包中的kml函数,但当我尝试在Qlik中读取它们时,它已损坏。 如果能对我上面的代码提供任何帮助