1

クライアントオブジェクトモデルを使用してSilverlightWebパーツを開発しています。SharePointサーバーからビットマップイメージを取得しています。次に、このビットマップイメージを分離ストレージに保存します。だから私は次のコードを使用しています

 WriteableBitmap wb = new WriteableBitmap(attachments);

 using (IsolatedStorageFile isoFile = IsolatedStorageFile.GetUserStoreForApplication())
 {
     using (IsolatedStorageFileStream isoStream =
     new IsolatedStorageFileStream("abcd1.jpg", FileMode.Create, isoFile))
     {
         using (StreamWriter sw = new StreamWriter(isoStream))
         {
             sw.Write(wb.ToByteArray());
         }
     }
 }

保存した画像がC:\ Users \ Rent2 \ AppData \ LocalLow \ Microsoft \ Silverlight \ is \ vzvpufsm.s4i \ m0laonzr.til \ 1 \ s \ nkhajster01es5wdoyfxd0n5rd2dls3ovyu4wcdig04zjx44hyaaafea\fに表示されています。

それをクリックすると、「無効な画像」というメッセージが表示されます。隔離されたストレージに保存した後に実際の画像を表示できるように、コードをどのように記述すればよいか教えてください。

4

3 に答える 3

1
    private void zipFile()
            {     
                context = Microsoft.SharePoint.Client.ClientContext.Current;
                Microsoft.SharePoint.Client.File.OpenBinaryDirect(
                        context,
                        @"/TemplateInvoice/" + App.templateFileName + ".xlsx", successFile, FailFile);                  
            }

    private void successFile(object sender, OpenBinarySucceededEventArgs args)
            {
                System.Windows.Deployment.Current.Dispatcher.BeginInvoke(() =>
                {
                    // Obtain the isolated storage for an application.
                    try
                    {
                        using (var store = IsolatedStorageFile.GetUserStoreForApplication())
                        {
                            Stream strm = args.Stream;

                            using (var isoStream = store.OpenFile(App.templateFileName + ".zip", FileMode.OpenOrCreate))
                            {
                                // Read the resource file into a byte array.
                                bytes = new byte[strm.Length];
                                int numBytesToRead = (int)strm.Length;
                                int numBytesRead = 0;
                                while (numBytesToRead > 0)
                                {
                                    // Read may return anything from 0 to numBytesToRead.
                                    int n = strm.Read(bytes, numBytesRead, numBytesToRead);
                                    // The end of the file is reached.
                                    if (n == 0)
                                        break;
                                    numBytesRead += n;
                                    numBytesToRead -= n;
                                }


                                numBytesToRead = bytes.Length;

                                // Write the byte array to the IsolatedStorageFileStream.
                                isoStream.Write(bytes, 0, numBytesToRead);
                                //isoStream.Dispose();
                            }

                            strm.Close();

                            string path = App.templateFileName + ".zip";
                            ZipHelp.UnZip(path, System.IO.Path.GetDirectoryName(path), 4096);

                            replaceFileContent();

                            string rootDirectory = System.Windows.Browser.HttpUtility.UrlDecode(path);
                            string fileName = ZipHelp.Zip(rootDirectory.Replace(".zip", ""), invoice);

                            //string filename = DateTime.Now.Day.ToString() + DateTime.Now.Month.ToString() + DateTime.Now.Year.ToString() + DateTime.Now.Hour.ToString() + DateTime.Now.Minute.ToString() + DateTime.Now.Second.ToString() + "Invoice1.xlsx";

                            // Read the resource file into a byte array.
                            using (var stream = store.OpenFile(fileName, FileMode.Open))
                            {

                                bytes = new byte[stream.Length];
                                int numBytesToRead = (int)stream.Length;
                                int numBytesRead = 0;
                                while (numBytesToRead > 0)
                                {
                                    // Read may return anything from 0 to numBytesToRead.
                                    int n = stream.Read(bytes, numBytesRead, numBytesToRead);
                                    // The end of the file is reached.
                                    if (n == 0)
                                        break;
                                    numBytesRead += n;
                                    numBytesToRead -= n;
                                }


                                InvoiceTemplete invoiceTemplate = new InvoiceTemplete(fileName, bytes, SetMessage);
                                invoiceTemplate.AddDocument(invoiceTemplate);
                            }

                        }

                        //mark rows as billed
                        foreach (var item in PrivatePayList)
                        {
                            MedwaiverViewModel MedwaiverViewModelObj = new MedwaiverViewModel();
                            MedwaiverViewModelObj.ChangeBillingStatus(item.ListItemId, "Billed");

                            if (MedwaiverTimeLogList != null)
                            {
                                MedwaiverTimeLogList.Remove(item);
                            }

                            if (ClientSpecificTimeLogList != null)
                            {
                                ClientSpecificTimeLogList.Remove(item);
                            }

                            if (rangeBoundTimeLogListForDate != null)
                            {
                                rangeBoundTimeLogListForDate.Remove(item);
                            }

                            if (vRangeBoundTimeLogListForDateAndClient != null)
                            {
                                vRangeBoundTimeLogListForDateAndClient.Remove(item);
                            }

                        }

                    }
                    catch (IsolatedStorageException isx)
                    {
                        MessageBox.Show(isx.Message);
                    }
                });
            }

     private void FailFile(object sender, OpenBinaryFailedEventArgs e)
            {
                System.Windows.Deployment.Current.Dispatcher.BeginInvoke(() =>
                {
                    MessageBox.Show("Fail");
                });
            }


//The following class zip and unzip the file

class ZipHelp
    {
        static List<string> folderPathList = new List<string>();      

        public static string Zip(string rootDirectory, string fileName)
        {
            byte[] buffer;

            using (var store = IsolatedStorageFile.GetUserStoreForApplication())
            {
                IsolatedStorageFileStream zipFileStream = store.CreateFile(fileName + ".xlsx");
                ZipOutputStream zipOutStream = new ZipOutputStream(zipFileStream);
                zipOutStream.UseZip64 = UseZip64.Off;
                //zipOutStream.CanPatchEntries

                foreach (var item in folderPathList)
                {
                    string entryName = "";

                    buffer = new byte[4096];

                    if (item.Substring(0,1) == @"/")
                    {
                        //removes leading /
                        entryName = item.Substring(1);
                    }
                    else
                    {
                        entryName = item;
                    }

                    ZipEntry entry = new ZipEntry(entryName);
                    //entry.CompressionMethod = CompressionMethod.Deflated;
                    //entry.
                    entry.IsZip64Forced();
                    //entry.IsDirectory



                    zipOutStream.PutNextEntry(entry);


                    using (IsolatedStorageFileStream stream = store.OpenFile(rootDirectory + @"\" + item, FileMode.Open))
                    {


int size;
                        do
                        {
                            size = stream.Read(buffer, 0, buffer.Length);
                            zipOutStream.Write(buffer, 0, size);
                        } while (size > 0);

                    stream.Close();
                }
            }

            zipOutStream.Close();
            zipFileStream.Close();
        }

        return fileName + ".xlsx";


        //string[] directories = GetLocationTypes();

        //zip();

        //string[] filenames = Directory.GetFiles(directories);

        //using (var store = IsolatedStorageFile.GetUserStoreForApplication())
        //{                
        //    using (var isoStream = store.OpenFile("@" + rootDirectory, FileMode.OpenOrCreate))
        //    {
        //        //foreach(string dir in 
        //    }
        //}
    }       

    private static string[] GetLocationTypes()
    {
        using (var store = IsolatedStorageFile.GetUserStoreForApplication())
        {
            return store.GetDirectoryNames();
        }

    }

    /// <summary>
    /// UnZip a file
    /// </summary>
    /// <param name="SrcFile">source file path</param>
    /// <param name="DstFile">unzipped file path</param>
    /// <param name="BufferSize">buffer to use</param>
    public static void UnZip(string SrcFile, string DstFile, int BufferSize)
    {
        folderPathList.Clear();

        IsolatedStorageFile store = IsolatedStorageFile.GetUserStoreForApplication();
        FileStream fileStreamIn = store.OpenFile(SrcFile, FileMode.Open, FileAccess.Read);

        ZipInputStream zipInStream = new ZipInputStream(fileStreamIn);
        string rootDirectory = System.Windows.Browser.HttpUtility.UrlDecode(SrcFile);
        rootDirectory = rootDirectory.Replace(".zip", "");
        store.CreateDirectory(rootDirectory);

        while (true)
        {
            ZipEntry entry = zipInStream.GetNextEntry();

            if (entry == null)
                break;

            if (entry.Name.Contains("/"))
            {
                string[] folders = entry.Name.Split('/');

                string lastElement = folders[folders.Length - 1];
                var folderList = new List<string>(folders);
                folderList.RemoveAt(folders.Length - 1);
                folders = folderList.ToArray();

                string folderPath = "";
                foreach (string str in folders)
                {
                    folderPath = folderPath + "/" + str;
                    if (!store.DirectoryExists(rootDirectory + "/" + folderPath))
                    {
                        store.CreateDirectory(rootDirectory + "/" + folderPath);
                    }
                }

                folderPath = folderPath + "/" + lastElement;
                writeToFile(BufferSize, fileStreamIn, zipInStream, rootDirectory, folderPath);

            }
            else
            {
                writeToFile(BufferSize, fileStreamIn, zipInStream, rootDirectory, entry.Name);
            }

        }

        zipInStream.Close();
        fileStreamIn.Close();

    }

    private static void writeToFile(int BufferSize, FileStream fileStreamIn, ZipInputStream zipInStream, string rootDirectory, string folderPath)
    {
        IsolatedStorageFile store1 = IsolatedStorageFile.GetUserStoreForApplication();
        FileStream fileStreamOut = store1.OpenFile(rootDirectory + "/" + folderPath, FileMode.Create, FileAccess.Write);

        folderPathList.Add(folderPath);

        int size;
        byte[] buffer = new byte[BufferSize];
        do
        {
            size = zipInStream.Read(buffer, 0, buffer.Length);
            fileStreamOut.Write(buffer, 0, size);
        } while (size > 0);


        fileStreamOut.Close();

    }
}
于 2012-01-11T06:24:41.677 に答える
0

ここで2つの実行可能なオプションを考えることができます。

  1. 上記のコードでは、WriteableBitmapのPixels配列を保存します。次に、それを復元するには、適切なサイズのWriteableBitmapを作成し、保存されているデータにPixels配列を設定します。

-また-

  1. HttpWebRequestまたはWebClientリクエストを使用して、生の画像ストリームを取得し、IsolatedStorageに保存します。

これらにはそれぞれ長所と短所があります。最初のケースでは、データは圧縮されておらず、分離されたストレージでより多くのスペースを占有し、上記の問題と同様に、Silverlightの外部のディスクからイメージを開くことができません。 。2番目のオプションでは、イメージがSilverlight XAPファイルとは異なるサーバー上にあり、実装が少し複雑な場合、クロスドメインの問題が発生する可能性があります。

于 2011-12-01T13:48:53.843 に答える
0

基本的な問題は、デコードされたRGBAピクセル配列をJPEGファイルとして保存していることですが、同じではありません。コードは基本的に正しいです。このメソッドを使用してJPEGファイルとして保存することはできません。ただし、画像がたとえば800x600であることがわかっている場合は、800x600のWriteableBitmapを作成してから、取得したストリームのバイト配列にPixelsプロパティを設定できます。または、取得するときに寸法がわからない場合は、(ストリームにピクセルを書き込む前に)ストリームの最初の2つの整数として寸法を保存し、読み取り時に寸法を読み取ることができます。ファイル。効果的に、独自の非常に単純な.bmp形式を作成することになります。

于 2011-12-01T16:44:11.803 に答える