クイック スタート: 記憶装置からの画像ファイルの取得 (HTML)

このチュートリアルでは、リムーバブル記憶装置から画像ファイルを取得して表示する方法について説明します。

目標: 前の例と同様、ポータブル記憶装置を列挙し、Windows.Devices.Portable.Storage.FromId を使ってインスタンス化します。ただし、この例では、createFileQueryWithOption を使って画像ファイルを検索し、getFilesAsync を使って取得します。

必要条件

JavaScript と HTML について理解している必要があります。

リムーバブル記憶装置が必要です。

完了までの時間: 20 分.

手順

1. Microsoft Visual Studio を開く

Visual Studio のインスタンスを開きます。

2. 新しいプロジェクトを作る

[新しいプロジェクト] ダイアログ ボックスで、JavaScript のプロジェクトの種類から新しいアプリケーションを選びます。

3. リムーバブル ストレージの機能を宣言する

ソリューション エクスプローラーで package.appxmanifest をダブルクリックします。[機能] タブをクリックします。[機能] の一覧で、[リムーバブル ストレージ] をオンにします。

4. ファイルの種類を宣言する

  1. [宣言] タブの [使用可能な宣言] から [File Type Declarations] (ファイルの種類の宣言) を選びます。
  2. [プロパティ] で、Name プロパティを image に設定します。
  3. [サポートされるファイルの種類] ボックスの [新規追加] をクリックし、サポートされるファイルの種類として .gif を追加します。FileType フィールドに「.gif」と入力してください。
  4. サポートされるファイルの種類をさらに 2 つ追加します (.jpg と .png)。[新規追加] をクリックして、FileType にそれぞれのファイルの種類を入力してください。

5. アプリケーションの HTML と JavaScript を挿入する

Default.html を開き、次のコードをこのファイルにコピーして、元の内容を置き換えます。

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <title>Get an image file from a removable storage device</title>
    
    <link rel="stylesheet" href="/winjs/css/ui-dark.css" />

    <script type = "text/javascript" >

    Enum = Windows.Devices.Enumeration;

    // Enumerate removable storage devices.
    // The success callback selects the removable storage to use.
    function pickStorageToGetImageFrom() {
        Enum.DeviceInformation.findAllAsync(
        Windows.Devices.Portable.StorageDevice.getDeviceSelector(),
        null).then(
            successCallback,
            errorCallback);
    }

    // Handler that's called when removable storages are found.
    // storageDevices: A collection of type
    // Windows.Devices.Enumeration.DeviceInformationCollection.
    // This example just takes the first storage found in the list.
    function successCallback(storageDevices) {
        var removableStorage = null;
        if (storageDevices.length) {
            try {
                // Create an IStorageItem from the first removable storage device
                removableStorage = Windows.Devices.Portable.StorageDevice.fromId(
                storageDevices.getAt(0).id);
                // document.getElementById("output").innerHTML = storageDevices.getAt(0).name; 
            } catch (e) {
                document.getElementById("output").innerHTML =
                "Error: " + e.message;
            }
            if (removableStorage != null) {
                getImageFiles(removableStorage);
            }
        } else {
            document.getElementById("output").innerHTML =
                "No removable storage devices were found.";
        }
    }

    // Error callback that's called if unable to enumerate all 
    // removable storages
    function errorCallback(e) {
        document.getElementById("output").innerHTML =
            "Error enumerating storages: " + e.message;
    }

    // Find the images on the removable storage and display the first one
    // in the <img> element.
    // storageItem: the item representing the removable storage
    function getImageFiles(removableStorage)
    {
        // Construct the query for image files
        var queryOptions = new Windows.Storage.Search.QueryOptions(
                    Windows.Storage.Search.CommonFileQuery.orderByName,
                    [".jpg", ".png", ".gif"]);
        var imageFileQuery = removableStorage.createFileQueryWithOptions(
            queryOptions);

        // Run the query for image files
        imageFileQuery.getFilesAsync().
                    then(
                        function (items) {
            displayFirstImage(items);
        },
                        function (e) {
            document.getElementById("output").innerHTML =
                "Error when looking for images on the removable storage: "
                + e.message;
        });
    }



    function displayFirstImage(items) {
        var found = false;
        for (var i = 0, l = items.length; i < l && !found; i++) {
            if (items[i].size > 0) { // display the first non-empty file
                displayImage(items[i]);
                found = true;
            }
        }

        if (!found) {
            // No files found matching our criteria
            document.getElementById("output").innerHTML =
                "No image files found on the removable storage.";
        }
    }

    function displayImage(imageFile) {
        document.getElementById("imageNameHolder").innerHTML =
            "Image file name: " + imageFile.name + "<br/>";

        // Setting 2nd parameter to 'false' cleans up the URL 
        // after first use. we set this because we only need 
        // to load the URL into the image tag once.
        document.getElementById("imageHolder").src =
            window.URL.createObjectURL(imageFile, false);
    }
    </script>
</head>
<body>

<div>
     <p>Finds and displays the first available image file
        (.jpg, .png, or .gif) on a removable storage device.</p>
     <button onclick="pickStorageToGetImageFrom()">Get Image File</button>
</div>

<div id="output"></div>
<div id="imageOutput">
     <img id="imageHolder" alt="image holder" src=""/><br />
     <div id="imageNameHolder"></div>
</div>
</body>
</html>

6. アプリケーションをテストする

  1. リムーバブル記憶装置を接続します (まだ接続していない場合)。
  2. [デバッグ][デバッグ開始] の順にクリックし、ソリューションをテストします。
  3. [Get Image File] (画像ファイルの取得) をクリックして、リムーバブル記憶装置上の最初の画像ファイルを取得して画像要素に表示します。

  エラーが発生した場合は、次の点を確認してください。

  • リムーバブル ストレージへのアクセスが有効になっていることを確認します。ソリューション エクスプローラーで package.appxmanifest を開き、[機能] タブの [リムーバブル ストレージ] を確認してください。

 

要約と次のステップ

この例では、findAllAsync からデバイス ID を取得し、その ID を Windows.Devices.Portable.Storage.FromId に渡してストレージ オブジェクトを作成した後、記憶装置内の画像にアクセスしました。

この例では、successHandler 関数で、列挙されたすべての記憶装置のうち、1 つ目の記憶装置を選びましたが、実際のアプリでは、利用可能なすべてのリムーバブル ストレージを一覧表示して、そこからユーザーに選んでもらうこともできます。

次のチュートリアルでは、自動再生ハンドラーを使ってストレージ オブジェクトを作成します。

関連トピック

クイック スタート: 一般的なデバイスの列挙

Windows Phone アプリでの SD カードへのアクセス