GetOutputStreamAt() public method

public GetOutputStreamAt ( [ position ) : IOutputStream
position [
return IOutputStream
Ejemplo n.º 1
0
 public IOutputStream GetOutputStreamAt(ulong position)
 {
     System.Diagnostics.Debug.WriteLine("GetOutputStreamAt: " + position.ToString());
     if (internalStream.Size > position)
     {
         return(internalStream.GetOutputStreamAt(position));
     }
     return(null);
 }
Ejemplo n.º 2
0
 public async static void GetImageSize(this Stream imageStream)
 {
     var image = new BitmapImage();
     byte[] imageBytes = Convert.FromBase64String(imageStream.ToBase64String());
     MemoryStream ms = new MemoryStream(imageBytes, 0, imageBytes.Length);
     ms.Write(imageBytes, 0, imageBytes.Length);
     using (InMemoryRandomAccessStream stream = new InMemoryRandomAccessStream())
     {
         using (DataWriter writer = new DataWriter(stream.GetOutputStreamAt(0)))
         {
             try
             {
                 writer.WriteBytes(imageBytes);
                 await writer.StoreAsync();
             }
             catch (Exception)
             {
                 // ignored
             }
         }
         try
         {
             await image.SetSourceAsync(stream);
         }
         catch (Exception)
         {
             // ignored
         }
     }
     ImageSize = new Size(image.PixelWidth, image.PixelHeight);
 }
        public object Convert(object value, Type targetType, object parameter, string language)
        {
            if (value != null)
            {

                byte[] bytes = (byte[])value;
                BitmapImage myBitmapImage = new BitmapImage();
                if (bytes.Count() > 0)
                {


                    InMemoryRandomAccessStream stream = new InMemoryRandomAccessStream();
                    DataWriter writer = new DataWriter(stream.GetOutputStreamAt(0));

                    writer.WriteBytes(bytes);
                    writer.StoreAsync().GetResults();
                    myBitmapImage.SetSource(stream);
                }
                else
                {
                    myBitmapImage.UriSource = new Uri("ms-appx:///Assets/firstBackgroundImage.jpg");
                }

                return myBitmapImage;
            }
            else
            {
                return new BitmapImage();
            }
        }
Ejemplo n.º 4
0
        public async Task<BitmapImage> GetBijinPicture(string Path)
        {
            var date = DateTime.Now;
            var url = "http://www.bijint.com/" + Path + "/tokei_images/" + date.ToString("HHmm") + ".jpg";

            HttpClient client = new HttpClient();
            client.DefaultRequestHeaders.Referrer = new Uri("http://www.bijint.com/" + Path);
            BitmapImage bitmap;
            using (var strm = await client.GetStreamAsync(new Uri(url)))
            {
                // BitmapImageインスタンスへはStream型をそのまま読み込ませることができないため、
                // InMemoryRandomAccessStreamへソースストリームをコピーする
                InMemoryRandomAccessStream ims = new InMemoryRandomAccessStream();
                var output = ims.GetOutputStreamAt(0);
                await RandomAccessStream.CopyAsync(strm.AsInputStream(), output);

                // BitmapImageへソースを設定し、Imageコントロールで表示させる
                bitmap = new BitmapImage();
                bitmap.SetSource(ims);
            }
            return bitmap;

            //var html = await client.GetStringAsync("http://www.bijint.com/kobe/cache/" + date.ToString("HHmm") + ".html");
            //this.html.NavigateToString(html);
        }
Ejemplo n.º 5
0
        private async void GetBijinPicture()
        {
            var date = DateTime.Now;
            var url = "http://www.bijint.com/jp/tokei_images/" + date.ToString("HHmm") + ".jpg";

            HttpClient client = new HttpClient();
            client.DefaultRequestHeaders.Referrer = new Uri("http://www.bijint.com/jp/");
            using (var strm = await client.GetStreamAsync(new Uri(url)))
            {
                // BitmapImageインスタンスへはStream型をそのまま読み込ませることができないため、
                // InMemoryRandomAccessStreamへソースストリームをコピーする
                InMemoryRandomAccessStream ims = new InMemoryRandomAccessStream();
                var output = ims.GetOutputStreamAt(0);
                await RandomAccessStream.CopyAsync(strm.AsInputStream(), output);

                // BitmapImageへソースを設定し、Imageコントロールで表示させる
                var bitmap = new BitmapImage();
                bitmap.SetSource(ims);
                image.Source = bitmap;

                // Save用にbyte配列に保存
                ims.Seek(0);
                imageBuffer = new byte[ims.Size];
                IBuffer ibuffer = imageBuffer.AsBuffer();
                await ims.ReadAsync(ibuffer, (uint)ims.Size, InputStreamOptions.None);
            }
        }
Ejemplo n.º 6
0
        public static async Task<IRandomAccessStream> ConvertToRandomAccessStream(Stream source)
        {
            Stream streamToConvert = null;
            
            if (!source.CanRead)
                throw new Exception("The source cannot be read.");

            if (!source.CanSeek)
            {
                var memStream = new MemoryStream();
                await source.CopyToAsync(memStream);
                streamToConvert = memStream;
            }
            else
            {
                streamToConvert = source;
            }

            var reader = new DataReader(streamToConvert.AsInputStream());
            streamToConvert.Position = 0;
            await reader.LoadAsync((uint) streamToConvert.Length);
            var buffer = reader.ReadBuffer((uint) streamToConvert.Length);

            var randomAccessStream = new InMemoryRandomAccessStream();
            var outputStream = randomAccessStream.GetOutputStreamAt(0);
            await outputStream.WriteAsync(buffer);
            await outputStream.FlushAsync();

            return randomAccessStream;
        }
Ejemplo n.º 7
0
        public object Convert(object value, Type targetType, object parameter, string language)
        {
            if (value != null && value is byte[])
            {

                //WriteableBitmap bitmap = new WriteableBitmap(100, 100);

                //System.IO.Stream bitmapStream = null;
                //bitmapStream = bitmap.PixelBuffer.AsStream();
                //bitmapStream.Position = 0;
                //bitmapStream.Write(value as byte[], 0, (value as byte[]).Length);

                //bitmapStream.Flush();

                InMemoryRandomAccessStream randomAccessStream = new InMemoryRandomAccessStream();
                DataWriter writer = new DataWriter(randomAccessStream.GetOutputStreamAt(0));
                writer.WriteBytes(value as byte[]);
                var x = writer.StoreAsync().AsTask().Result;
                BitmapImage image = new BitmapImage();
                image.SetSource(randomAccessStream);

                return image;
            }

            return null;
        }
Ejemplo n.º 8
0
        public async static Task<IRandomAccessStream> AsRandomAccessStreamAsync(this Stream stream)
        {
            Stream streamToConvert = null;

            if (!stream.CanRead)
            {
                throw new Exception("Cannot read the source stream-");
            }
            if (!stream.CanSeek)
            {
                MemoryStream memoryStream = new MemoryStream();
                await stream.CopyToAsync(memoryStream);
                streamToConvert = memoryStream;
            }
            else
            {
                streamToConvert = stream;
            }

            DataReader dataReader = new DataReader(streamToConvert.AsInputStream());
            streamToConvert.Position = 0;
            await dataReader.LoadAsync((uint)streamToConvert.Length);
            IBuffer buffer = dataReader.ReadBuffer((uint)streamToConvert.Length);

            InMemoryRandomAccessStream randomAccessStream = new InMemoryRandomAccessStream();
            IOutputStream outputstream = randomAccessStream.GetOutputStreamAt(0);
            await outputstream.WriteAsync(buffer);
            await outputstream.FlushAsync();

            return randomAccessStream;
        }
Ejemplo n.º 9
0
        public object Convert(object value, Type targetType, object parameter, string language)
        {
            if (!(value is byte[]))
            {
                return null;
            }

            using (InMemoryRandomAccessStream ms = new InMemoryRandomAccessStream())
            {
                // Writes the image byte array in an InMemoryRandomAccessStream
                // that is needed to set the source of BitmapImage.
                using (DataWriter writer = new DataWriter(ms.GetOutputStreamAt(0)))
                {
                    writer.WriteBytes((byte[])value);

                    // The GetResults here forces to wait until the operation completes
                    // (i.e., it is executed synchronously), so this call can block the UI.
                    writer.StoreAsync().GetResults();
                }

                var image = new BitmapImage();
                image.SetSource(ms);
                return image;
            }
        }
Ejemplo n.º 10
0
        private async void Update()
        {
            var writer1 = new BarcodeWriter
            {
                Format = BarcodeFormat.QR_CODE,
                Options = new ZXing.Common.EncodingOptions
                {
                    Height = 200,
                    Width = 200
                },

            };

            var image = writer1.Write(Text);//Write(text);


            using (InMemoryRandomAccessStream ms = new InMemoryRandomAccessStream())
            {
                using (DataWriter writer = new DataWriter(ms.GetOutputStreamAt(0)))
                {
                    writer.WriteBytes(image);
                    await writer.StoreAsync();
                }

                var output = new BitmapImage();
                await output.SetSourceAsync(ms);
                ImageSource = output;
            }


        }
Ejemplo n.º 11
0
        // TODO: 一分ごとに画像と名前を取得する
        private async void GetBijinInfo()
        {
            var date = this.Current;
            getKawaii(this.path + this.Current.ToString("HHmm"));
            var url = "http://www.bijint.com/" + Path + "/tokei_images/" + date.ToString("HHmm") + ".jpg";

            HttpClient client = new HttpClient();
            client.DefaultRequestHeaders.Referrer = new Uri("http://www.bijint.com/" + path);
            using (var strm = await client.GetStreamAsync(new Uri(url)))
            {
                // BitmapImageインスタンスへはStream型をそのまま読み込ませることができないため、
                // InMemoryRandomAccessStreamへソースストリームをコピーする

                InMemoryRandomAccessStream ims = new InMemoryRandomAccessStream();
                
                var output = ims.GetOutputStreamAt(0);
                await RandomAccessStream.CopyAsync(strm.AsInputStream(), output);

                // BitmapImageへソースを設定し、Imageコントロールで表示させる
                var bitmap = new BitmapImage();
                bitmap.SetSource(ims);
                this.Image = bitmap;
            }

            var html = await client.GetStringAsync("http://www.bijint.com/" + Path + "/cache/" + date.ToString("HHmm") + ".html");
            var lines = html.Split('\n').Select(input => input.Trim()).Where(input => input != "\r" || input != "").ToList();
            var nameLineIndex = lines.IndexOf("<thead>") + 2;
            var nameLine = lines[nameLineIndex];
            var temp = nameLine.Substring(0, nameLine.Length - 5);
            var lastEnd = temp.LastIndexOf('>');
            this.Subtitle = temp.Substring(lastEnd + 1);


        }
Ejemplo n.º 12
0
 public async Task<IRandomAccessStream> Stream2IRandomAccessStream(byte[] bytes)
 {
     InMemoryRandomAccessStream memoryStream = new InMemoryRandomAccessStream();
     DataWriter datawriter = new DataWriter(memoryStream.GetOutputStreamAt(0));
     datawriter.WriteBytes(bytes);
     await datawriter.StoreAsync();
     return memoryStream;
 }
Ejemplo n.º 13
0
		private async void ColorThread()
		{
			try
			{
                var reader = new DataReader( Client.InputStream );
                reader.InputStreamOptions = InputStreamOptions.Partial;
                reader.ByteOrder = ByteOrder.LittleEndian;

                while ( IsConnected ) {
                    await reader.LoadAsync( 4 );
                    var size = reader.ReadUInt32();

                    await reader.LoadAsync( size );
                    byte[] bytes = new byte[size];
                    reader.ReadBytes( bytes );

                    MemoryStream ms = new MemoryStream( bytes );
					BinaryReader br = new BinaryReader(ms);

                    ColorFrameReadyEventArgs args = new ColorFrameReadyEventArgs();
                    ColorFrameData cfd = new ColorFrameData();

                    cfd.Format = (ImageFormat)br.ReadInt32();
					cfd.ImageFrame = br.ReadColorImageFrame();

                    MemoryStream msData = new MemoryStream( bytes, (int)ms.Position, (int)(ms.Length - ms.Position) );
                    if (cfd.Format == ImageFormat.Raw)
                    {
                        cfd.RawImage = ms.ToArray();
                    }
                    else
                    {
                        InMemoryRandomAccessStream ras = new InMemoryRandomAccessStream();
                        DataWriter dw = new DataWriter(ras.GetOutputStreamAt(0));
                        dw.WriteBytes(msData.ToArray());
                        await dw.StoreAsync();   

                        // Set to the image
                        BitmapImage bImg = new BitmapImage();
                        bImg.SetSource(ras);
                        cfd.BitmapImage = bImg;
                    }

					ColorFrame = cfd;
					args.ColorFrame = cfd;

                    if (ColorFrameReady != null)
                    {
                        ColorFrameReady(this, args);
                    }
				}
			}
			catch(IOException)
			{
				Disconnect();
			}
		}
Ejemplo n.º 14
0
 public static InMemoryRandomAccessStream AsInMemoryRandomAccessStream(byte[] data)
 {
     InMemoryRandomAccessStream randomAccessStream = new InMemoryRandomAccessStream();
     using (DataWriter writer = new DataWriter(randomAccessStream.GetOutputStreamAt(0)))
     {
         writer.WriteBytes(data);
         writer.StoreAsync().GetResults();
     }
     return randomAccessStream;
 }
 public static async Task<IRandomAccessStream> ConvertToRandomAccessStream(MemoryStream memoryStream)
 {
     var randomAccessStream = new InMemoryRandomAccessStream();
     var outputStream = randomAccessStream.GetOutputStreamAt(0);
     var dw = new DataWriter(outputStream);
     var task = Task.Factory.StartNew(() => dw.WriteBytes(memoryStream.ToArray()));
     await task;
     await dw.StoreAsync();
     await outputStream.FlushAsync();
     return randomAccessStream;
 }
Ejemplo n.º 16
0
        private async Task <Windows.Storage.Streams.IRandomAccessStream> toStream(Windows.Storage.Streams.IBuffer ibuffer)
        {
            var stream       = new Windows.Storage.Streams.InMemoryRandomAccessStream();
            var outputStream = stream.GetOutputStreamAt(0);
            var datawriter   = new Windows.Storage.Streams.DataWriter(outputStream);

            datawriter.WriteBuffer(ibuffer);
            await datawriter.StoreAsync();

            await outputStream.FlushAsync();

            return(stream);
        }
Ejemplo n.º 17
0
        public void DrawImage(Point center, Size s, Byte[] img_bytes)
        {

            InMemoryRandomAccessStream ms = new InMemoryRandomAccessStream();
            DataWriter writer = new DataWriter(ms.GetOutputStreamAt(0));
            writer.WriteBytes(img_bytes);
            writer.StoreAsync().GetResults();
            BitmapImage image = new BitmapImage();
            image.SetSource(ms);

            DrawImage(center, s, image);

        }
Ejemplo n.º 18
0
        private async Task<BitmapImage> ImageStreamAsyn(string url)
        {
            var response = await (new SPDocument()).GetDocument(url);

            using (InMemoryRandomAccessStream stream = new InMemoryRandomAccessStream())
            {
                DataWriter writer = new DataWriter(stream.GetOutputStreamAt(0));
                writer.WriteBytes(response);
                await writer.StoreAsync();
                BitmapImage b = new BitmapImage();
                b.SetSource(stream);
                return b;
            }
        }
Ejemplo n.º 19
0
        public async Task<string> Decrypt(IBuffer buffProtected, BinaryStringEncoding encoding)
        {
            try
            {
                // Create a DataProtectionProvider object.
                DataProtectionProvider Provider = new DataProtectionProvider();

                // Create a random access stream to contain the encrypted message.
                InMemoryRandomAccessStream inputData = new InMemoryRandomAccessStream();

                // Create a random access stream to contain the decrypted data.
                InMemoryRandomAccessStream unprotectedData = new InMemoryRandomAccessStream();

                // Retrieve an IOutputStream object and fill it with the input (encrypted) data.
                IOutputStream outputStream = inputData.GetOutputStreamAt(0);
                DataWriter writer = new DataWriter(outputStream);
                writer.WriteBuffer(buffProtected);
                await writer.StoreAsync();
                await outputStream.FlushAsync();

                // Retrieve an IInputStream object from which you can read the input (encrypted) data.
                IInputStream source = inputData.GetInputStreamAt(0);

                // Retrieve an IOutputStream object and fill it with decrypted data.
                IOutputStream dest = unprotectedData.GetOutputStreamAt(0);
                await Provider.UnprotectStreamAsync(source, dest);
                await dest.FlushAsync();

                // Write the decrypted data to an IBuffer object.
                DataReader reader2 = new DataReader(unprotectedData.GetInputStreamAt(0));
                await reader2.LoadAsync((uint)unprotectedData.Size);
                IBuffer buffUnprotectedData = reader2.ReadBuffer((uint)unprotectedData.Size);

                // Convert the IBuffer object to a string using the same encoding that was
                // used previously to conver the plaintext string (before encryption) to an
                // IBuffer object.
                String strUnprotected = CryptographicBuffer.ConvertBinaryToString(encoding, buffUnprotectedData);

                // Return the decrypted data.
                return strUnprotected;
            }
            catch (Exception ex)
            {
                App.Telemetry.TrackException(ex);
                return "";

            }

        }
        public object Convert(object value, Type targetType, object parameter, string language)
        {
            byte[] imageBytes = (byte[])value;
            var memoryStream = new InMemoryRandomAccessStream();
            using (var dataWriter = new DataWriter(memoryStream.GetOutputStreamAt(0)))
            {
                dataWriter.WriteBytes(imageBytes);

                dataWriter.StoreAsync().GetResults();
            }

            var bitmapImage = new BitmapImage();
            bitmapImage.SetSource(memoryStream);
            return bitmapImage;
        }
Ejemplo n.º 21
0
 //converts byte[] to BitmapImage
 public static BitmapImage ConvertImage(byte[] pictureBytes)
 {
     if (pictureBytes == null) return null;
     using (var ms = new InMemoryRandomAccessStream())
     {
         using (var writer = new DataWriter(ms.GetOutputStreamAt(0)))
         {
             writer.WriteBytes(pictureBytes);
             writer.StoreAsync().GetResults();
         }
         var image = new BitmapImage();
         image.SetSource(ms);
         return image;
     }
 }
        private async Task LoadMyEbooksAsync()
        {
            List<EbookViewModel> viewModels = new List<EbookViewModel>();
            var ebooks = await new GetMyEbooksQuery().ExecuteAsync(OAuthSettings.AccessToken);
            foreach (var ebook in ebooks)
            {
                var img = new BitmapImage();
                var stream = new Windows.Storage.Streams.InMemoryRandomAccessStream();
                stream.GetOutputStreamAt(0).AsStreamForWrite().Write(ebook.Thumbnail, 0, ebook.Thumbnail.Length);
                await img.SetSourceAsync(stream);
                viewModels.Add(new EbookViewModel(ebook, img));
            }
            flipMyBooks.ItemsSource = viewModels;

        }
Ejemplo n.º 23
0
        /// <summary>
        /// Use for small assets
        /// </summary>
        /// <param name="url"></param>
        /// <param name="cancelToken"></param>
        /// <returns></returns>
        public static async Task<IRandomAccessStream> DownloadFileAsync(LibrelioUrl url, CancellationToken cancelToken = default(CancellationToken))
        {
            var stream = new InMemoryRandomAccessStream();

            using(var response = await new HttpClient().GetAsync(url.AbsoluteUrl))
            {
                var buffer = await response.Content.ReadAsStringAsync();
                var dataWriter = new DataWriter(stream.GetOutputStreamAt(0));
                dataWriter.WriteString(buffer);
                await dataWriter.StoreAsync();
                await dataWriter.FlushAsync();
            }

            return stream;
        }
Ejemplo n.º 24
0
 private async Task LoadImageAsync()
 {
     using (InMemoryRandomAccessStream ms = new InMemoryRandomAccessStream())
     {
         // Writes the image byte array in an InMemoryRandomAccessStream
         // that is needed to set the source of BitmapImage.
         using (DataWriter writer = new DataWriter(ms.GetOutputStreamAt(0)))
         {
             writer.WriteBytes(User.UserPic);
             await writer.StoreAsync();
         }
         var image = new BitmapImage();
         await image.SetSourceAsync(ms);
         ImageSource = image;
     }
 }
Ejemplo n.º 25
0
        private async Task LoadMyEbooksAsync()
        {
            List <EbookViewModel> viewModels = new List <EbookViewModel>();
            var ebooks = await new GetMyEbooksQuery().ExecuteAsync(OAuthSettings.AccessToken);

            foreach (var ebook in ebooks)
            {
                var img    = new BitmapImage();
                var stream = new Windows.Storage.Streams.InMemoryRandomAccessStream();
                stream.GetOutputStreamAt(0).AsStreamForWrite().Write(ebook.Thumbnail, 0, ebook.Thumbnail.Length);
                await img.SetSourceAsync(stream);

                viewModels.Add(new EbookViewModel(ebook, img));
            }
            flipMyBooks.ItemsSource = viewModels;
        }
Ejemplo n.º 26
0
        /// <summary>
        /// Use for small assets
        /// </summary>
        /// <param name="url"></param>
        /// <param name="cancelToken"></param>
        /// <returns></returns>
        public static async Task<IRandomAccessStream> DownloadFileAsync(LibrelioUrl url, CancellationToken cancelToken = default(CancellationToken))
        {
            var stream = new InMemoryRandomAccessStream();
            var client = new HttpClient();
            client.DefaultRequestHeaders.Add("user-agent", "LibrelioWinRT");

            using (var response = await client.GetAsync(url))
            {
                var buffer = await response.Content.ReadAsStringAsync();
                var dataWriter = new DataWriter(stream.GetOutputStreamAt(0));
                dataWriter.WriteString(buffer);
                await dataWriter.StoreAsync();
                await dataWriter.FlushAsync();
            }

            return stream;
        }
Ejemplo n.º 27
0
        public object Convert(object value, Type targetType, object parameter, string language)
        {
            if (value == null || !(value is byte[]))
                return null;

            using (InMemoryRandomAccessStream ms = new InMemoryRandomAccessStream())
            {
                using (DataWriter writer = new DataWriter(ms.GetOutputStreamAt(0)))
                {
                    writer.WriteBytes((byte[])value);
                    writer.StoreAsync().GetResults();
                }
                var image = new BitmapImage();
                image.SetSource(ms);
                return image;
            }
        }
Ejemplo n.º 28
0
        public static BitmapImage DecodeToBitmapImage(string base64string)
        {
            var imageBytes = Convert.FromBase64String(base64string);
            BitmapImage image;
            using(InMemoryRandomAccessStream ms = new InMemoryRandomAccessStream())
            {
                using(DataWriter writer = new DataWriter(ms.GetOutputStreamAt(0)))
                {
                    writer.WriteBytes((byte[])imageBytes);
                    writer.StoreAsync().GetResults();
                }

                image = new BitmapImage();
                image.SetSource(ms);
            }
            return image;
        }
Ejemplo n.º 29
0
 public async Task<IRandomAccessStream> GetRandomStream()
 {
     if (Data == null)
     {
         return null;
     }
     else
     {
         var buffer = this.GetBuffer();
         InMemoryRandomAccessStream inStream = new InMemoryRandomAccessStream();
         DataWriter datawriter = new DataWriter(inStream.GetOutputStreamAt(0));
         datawriter.WriteBuffer(buffer, 0, buffer.Length);
         await datawriter.StoreAsync();
         return inStream;
     }
   
 }
Ejemplo n.º 30
0
        public static BitmapImage ConvertArrayBytesToImage(byte[] arquivo)
        {
            BitmapImage image = null;
            using (InMemoryRandomAccessStream ms = new InMemoryRandomAccessStream())
            {
                using (DataWriter writer = new DataWriter(ms.GetOutputStreamAt(0)))
                {
                    writer.WriteBytes(arquivo);
                    writer.StoreAsync().GetResults();
                }

                image = new BitmapImage();
                image.SetSource(ms);
            }

            return image;
        }
Ejemplo n.º 31
0
        private static async Task<bool> DownloadArtistPictureFromDeezer(MusicLibraryViewModel.ArtistItem artist)
        {
            var deezerClient = new DeezerClient();
            var deezerArtist = await deezerClient.GetArtistInfo(artist.Name);
            if (deezerArtist == null) return false;
            if (deezerArtist.Images == null) return false;
            try
            {
                var clientPic = new HttpClient();
                HttpResponseMessage responsePic = await clientPic.GetAsync(deezerArtist.Images.LastOrDefault().Url);
                string uri = responsePic.RequestMessage.RequestUri.AbsoluteUri;
                // A cheap hack to avoid using Deezers default image for bands.
                if (uri.Equals("http://cdn-images.deezer.com/images/artist//400x400-000000-80-0-0.jpg"))
                {
                    return false;
                }
                byte[] img = await responsePic.Content.ReadAsByteArrayAsync();
                InMemoryRandomAccessStream streamWeb = new InMemoryRandomAccessStream();
                DataWriter writer = new DataWriter(streamWeb.GetOutputStreamAt(0));
                writer.WriteBytes(img);
                await writer.StoreAsync();
                StorageFolder artistPic = await ApplicationData.Current.LocalFolder.CreateFolderAsync("artistPic",
                    CreationCollisionOption.OpenIfExists);
                string fileName = artist.Name + "_" + "dPi";
                var file = await artistPic.CreateFileAsync(fileName + ".jpg", CreationCollisionOption.OpenIfExists);
                var raStream = await file.OpenAsync(FileAccessMode.ReadWrite);

                using (var thumbnailStream = streamWeb.GetInputStreamAt(0))
                {
                    using (var stream = raStream.GetOutputStreamAt(0))
                    {
                        await RandomAccessStream.CopyAsync(thumbnailStream, stream);
                    }
                }
                StorageFolder appDataFolder = ApplicationData.Current.LocalFolder;
                string supposedPictureUriLocal = appDataFolder.Path + "\\artistPic\\" + artist.Name + "_" + "dPi" + ".jpg";
                await DispatchHelper.InvokeAsync(() => artist.Picture = supposedPictureUriLocal);
                return true;
            }
            catch (Exception)
            {
                Debug.WriteLine("Error getting or saving art from deezer.");
                return false;
            }
        }
Ejemplo n.º 32
0
        public async Task<IBuffer> Encrypt(string descriptor, string strMsg, BinaryStringEncoding encoding)
        {
            // Create a DataProtectionProvider object for the specified descriptor.
            DataProtectionProvider Provider = new DataProtectionProvider(descriptor);

            // Convert the input string to a buffer.
            IBuffer buffMsg = CryptographicBuffer.ConvertStringToBinary(strMsg, encoding);

            // Create a random access stream to contain the plaintext message.
            InMemoryRandomAccessStream inputData = new InMemoryRandomAccessStream();

            // Create a random access stream to contain the encrypted message.
            InMemoryRandomAccessStream protectedData = new InMemoryRandomAccessStream();

            // Retrieve an IOutputStream object and fill it with the input (plaintext) data.
            IOutputStream outputStream = inputData.GetOutputStreamAt(0);
            DataWriter writer = new DataWriter(outputStream);
            writer.WriteBuffer(buffMsg);
            await writer.StoreAsync();
            await outputStream.FlushAsync();

            // Retrieve an IInputStream object from which you can read the input data.
            IInputStream source = inputData.GetInputStreamAt(0);

            // Retrieve an IOutputStream object and fill it with encrypted data.
            IOutputStream dest = protectedData.GetOutputStreamAt(0);
            await Provider.ProtectStreamAsync(source, dest);
            await dest.FlushAsync();

            //Verify that the protected data does not match the original
            DataReader reader1 = new DataReader(inputData.GetInputStreamAt(0));
            DataReader reader2 = new DataReader(protectedData.GetInputStreamAt(0));
            await reader1.LoadAsync((uint)inputData.Size);
            await reader2.LoadAsync((uint)protectedData.Size);
            IBuffer buffOriginalData = reader1.ReadBuffer((uint)inputData.Size);
            IBuffer buffProtectedData = reader2.ReadBuffer((uint)protectedData.Size);

            if (CryptographicBuffer.Compare(buffOriginalData, buffProtectedData))
            {
                throw new Exception("ProtectStreamAsync returned unprotected data");
            }

            // Return the encrypted data.
            return buffProtectedData;
        }
Ejemplo n.º 33
0
    /// <summary>
    /// 指定範囲のキャプチャ画像をSoftwareBitmap型として得る
    /// </summary>
    /// <param name="left">キャプチャ範囲の左端端x座標</param>
    /// <param name="top">キャプチャ範囲の左端端y座標</param>
    /// <param name="height">キャプチャ範囲の高さ</param>
    /// <param name="width">キャプチャ範囲の幅</param>
    /// <returns>指定された範囲のキャプチャ画像</returns>
    public static async Task <SoftwareBitmap> CaptureAsSoftwareBitmap(int left, int top, int height, int width)
    {
        //ビットマップの保持領域を確保
        Bitmap partialCapture = new Bitmap(width, height);
        //描画インターフェイスの設定
        Graphics draw = Graphics.FromImage(partialCapture);

        //画面全体をコピーする
        draw.CopyFromScreen(
            left,
            top,
            0, 0,
            partialCapture.Size
            );

        //解放
        draw.Dispose();

        MemoryStream memStream = new MemoryStream();

        partialCapture.Save(memStream, ImageFormat.Bmp);

        SoftwareBitmap softwareBitmap;

        using (var randomAccessStream = new UwpInMemoryRandomAccessStream())
        {
            using (var outputStream = randomAccessStream.GetOutputStreamAt(0))
                using (var writer = new UwpDataWriter(outputStream))
                {
                    writer.WriteBytes(memStream.ToArray());
                    await writer.StoreAsync();

                    await outputStream.FlushAsync();
                }

            // IRandomAccessStreamをSoftwareBitmapに変換
            // (ここはUWP APIのデコーダーを使う)
            var decoder = await UwpBitmapDecoder.CreateAsync(randomAccessStream);

            softwareBitmap = await decoder.GetSoftwareBitmapAsync(UwpBitmapPixelFormat.Bgra8, UwpBitmapAlphaMode.Premultiplied);
        }

        return(softwareBitmap);
    }
        public void LoadFromResource(string assemblyName, MvxResourcePath resourceName)
        {
            //Package.Current.InstalledLocation.GetFileAsync()
            var path = resourceName.GetResourcePath(".", true);
            //   bitmap = new BitmapImage(new Uri("ms-appx:///" + assemblyName + "/" + path, UriKind.RelativeOrAbsolute));
            var strm = Assembly.Load(new AssemblyName(assemblyName)).GetManifestResourceStream(path);
            byte[] bts = new byte[strm.Length];
            strm.Read(bts, 0, (int)strm.Length);
            InMemoryRandomAccessStream ras = new InMemoryRandomAccessStream();

            ras.GetOutputStreamAt(0).WriteAsync(bts.AsBuffer());
            //strm.CopyToAsync(ras.AsStreamForWrite()).Wait();

            ras.Seek(0);
            bitmap = new BitmapImage();
            bitmap.SetSource(ras);
            ras.Dispose();
            strm.Dispose();
        }
Ejemplo n.º 35
0
        private async Task updateImage(Image cameraImage, string url)
        {
            // Download the image into memory as a stream
            System.Net.Http.HttpClient          client        = new System.Net.Http.HttpClient();
            System.Net.Http.HttpResponseMessage imageResponse = await client.GetAsync(url);

            InMemoryRandomAccessStream randomAccess =
                new Windows.Storage.Streams.InMemoryRandomAccessStream();

            DataWriter writer =
                new Windows.Storage.Streams.DataWriter(randomAccess.GetOutputStreamAt(0));

            writer.WriteBytes(await imageResponse.Content.ReadAsByteArrayAsync());
            await writer.StoreAsync();

            BitmapImage bit = new BitmapImage();
            await bit.SetSourceAsync(randomAccess);

            cameraImage.Source = bit;
        }
Ejemplo n.º 36
0
        private async void Stream_Click1(object sender, RoutedEventArgs e)
        {
            byte[] startSequence = { 0, 0, 0, 1, 0x27, 0x4d };
            var    options       = new PropertySet();

            //options.Add("framerate", "25");
            //options.Add("vcodec", "copy");

            _ws = new StreamWebSocket();
            await _ws.ConnectAsync(new Uri(wsuri.Text, UriKind.Absolute));

            bool isStarted = false;
            bool isCreated = false;

            var stream = new Windows.Storage.Streams.InMemoryRandomAccessStream();
            var output = stream.GetOutputStreamAt(0);
            var writer = new DataWriter(output);

            int        maxdelay = 10;
            int        delay    = maxdelay;
            int        index    = 0;
            DataReader reader   = new DataReader(_ws.InputStream);

            do
            {
                var loaded = await reader.LoadAsync(10 * 1024);

                var buf = reader.ReadBuffer(loaded);
                if (!isStarted)
                {
                    isStarted = true;
                    var signature = buf.ToArray();
                    index = Helpers.FindSequence(signature, 0, startSequence);
                    if (index == -1)
                    {
                        Debug.WriteLine("signature not found, continuing");
                        continue;
                    }

                    buf = signature.AsBuffer(index, signature.Length - index);
                    Debug.WriteLine("buffer created");
                    //await output.WriteAsync(buf);
                    writer.WriteBuffer(buf);
                }
                else
                {
                    //await output.WriteAsync(buf);
                    //await output.FlushAsync();
                    writer.WriteBuffer(buf);
                }

                await writer.StoreAsync();

                if (delay > 0)
                {
                    delay--;
                    Debug.Write("B");
                    //Debug.WriteLine(stream.Position);
                    continue;
                }
                //delay = maxdelay;

                //Debug.Write(".");
                try
                {
                    //await output.WriteAsync(buf);
                    if (!isCreated)
                    {
                        isCreated = true;
                        //stream.Seek((ulong)0);
                        var decoder = FFmpegInterop.FFmpegInteropMSS.CreateFFmpegInteropMSSFromStream(
                            stream, false, false, options);
                        if (decoder == null)
                        {
                            Debug.WriteLine("decoder was null, will retry");
                            continue;
                        }

                        var source = decoder.GetMediaStreamSource();
                        source.Closed          += Source_Closed;
                        source.Starting        += Source_Starting;
                        source.SampleRequested += Source_SampleRequested;
                        source.SampleRendered  += Source_SampleRendered;
                        //source.BufferTime = TimeSpan.FromSeconds(0.2);

                        media.SetMediaStreamSource(source);
                        media.Play();
                    }
                }
                catch (Exception err)
                {
                    Debug.WriteLine(err.ToString());
                    stream.Dispose();
                    reader.Dispose();
                    return;
                }
            }while (true);
        }