共用方式為


如何讀取影像中繼資料 (HTML)

[ 本文的目標對象是撰寫 Windows 執行階段 App 的 Windows 8.x 和 Windows Phone 8.x 開發人員。如果您正在開發適用於 Windows 10 的 App,請參閱 最新文件 ]

這裡將說明如何從影像檔擷取中繼資料。 影像格式如 JPEG、TIFF 和 PNG 支援各種不同的內嵌中繼資料,這些資料會描述像是關鍵字、GPS 位置和相機資訊等。您可以存取常用的影像屬性,以及存放在 EXIF 和 XMP 這類格式中更進階的原始中繼資料。

根據情況而定,有兩種類別可以存取影像中繼資料:Windows.Storage.FileProperties.ImagePropertiesWindows.Graphics.Imaging.BitmapPropertiesView

您可以使用 BitmapPropertiesView 取得 Windows 屬性,像是 ImageProperties。但是它使用 WIC 中繼資料查詢語言,對檔案中的原生中繼資料結構提供較低層級的存取。存取原生中繼資料是較進階的情況,但是能夠讓您存取比 Windows 屬性系統所提供更多的中繼資料。

您必須知道的事

技術

先決條件

指示

步驟 1: 取得解碼器物件

編寫函式時一開始要接收 BitmapDecoder 物件,並宣告要存放您所擷取之屬性的變數。

(function (decoder) {
      var orientation;
      var xmpCreator;

使用解碼器存取影像中繼資料。 如果您還沒有解碼器物件,請參閱如何解碼影像。 在這裡宣告變數,使其保持在範圍內。

步驟 2: 擷取 Windows 屬性

BitmapDecoder 類別有一個 BitmapPropertiesView 類型的成員 BitmapProperties。就像 ImageProperties,您可以藉由將屬性機碼名稱清單傳遞至 bitmapProperties.getPropertiesAsync,以非同步的方式要求支援的 Windows 屬性。

注意  並非每一種格式都支援所有屬性。相片中繼資料原則會列出哪些影像格式支援各種屬性。

 

     return 
decoder.bitmapProperties.getPropertiesAsync(["System.Photo.Orientation"])
     .then(function(retrievedProps) {

BitmapPropertiesViewImageProperties 的行為有幾項重要的差異:

  • 您必須先檢查屬性是否存在,才能從集合中進行擷取。如果屬性不存在,這個方法會傳回錯誤。
  • 每個屬性值都是 BitmapTypedValue 類型。這個物件有一個包含實際資料的 Value 成員,和一個表示資料的 Type 成員。
  • 如果影像格式不支援您要求的屬性,BitmapPropertiesView 會傳回錯誤。您需要處理這些錯誤,或是確保程式碼僅要求影像格式支援的屬性。例如,BMP 檔不包含任何中繼資料。

以下說明如何查詢屬性:

if (retrievedProperties.hasKey("System.Photo.Orientation") {
        orientation = retrievedProperties.lookup("System.Photo.Orientation").value;
    }     
}, function (error) {
    switch (error.number) {
        case -2003292287:
            // The image format does not support this property.
            break;
        case -2003292287:
            // The image format does not support metadata.
            break;
        default:
            // Catch any other errors.
            break;
    }
});

步驟 3: 擷取原生影像中繼資料

雖然 ImageProperties 僅限於 Windows 屬性,但是 BitmapPropertiesView 可以讓您存取存放在影像內的大部分中繼資料。如需每個點陣圖轉碼器支援的中繼資料格式清單,請參閱原生影像格式中繼資料查詢

您可以使用 WIC 中繼資料查詢語言查詢屬性,用法與 System.Photo 屬性類似。您將屬性名稱取代為中繼資料查詢字串。

將您在步驟 2 中編寫的程式碼取代為這個程式碼:

return decoder.bitmapProperties.getPropertiesAsync(["/xmp/dc:creator"])
.then(function(retrievedProps) {
    if (retrievedProperties.hasKey("/xmp/dc:creator") {
        xmpCreator = retrievedProperties.lookup("/xmp/dc:creator").value;
    }     
}, function (error) {
    switch (error.number) {
        case -2003292287:
            // The image format does not support this property.
            break;
        case -2003292287:
            // The image format does not support metadata.
            break;
        default:
            // Catch any other errors.
            break;
    }
});

這個特定的程式碼片段會要求 Dublin Core XMP 結構描述中所定義的建立者中繼資料。查詢 "/xmp/dc:creator" 只對 JPEG 影像有效。例如,TIFF 影像同樣支援 XMP 中繼資料,但是對等的 TIFF 查詢為 "/ifd/xmp/dc:creator"。

相關主題

如何解碼影像

中繼資料查詢語言概觀

System.Photo 屬性

如何寫入影像中繼資料

相片中繼資料原則