コード例 #1
0
        private async Task SaveStrokesToBitmap(WriteableBitmap b)
        {
            Rect imgRect = new Rect(0, 0, b.PixelWidth, b.PixelHeight);
            InkStrokeContainer container = TheInkCanvas.InkPresenter.StrokeContainer;
            InkStrokeBuilder builder = new InkStrokeBuilder();

            // Unsichtbare Tinte!
            InkDrawingAttributes da = TheInkCanvas.InkPresenter.CopyDefaultDrawingAttributes();
            da.Size = new Size(0.1, 0.1);
            builder.SetDefaultDrawingAttributes(da);

            // Strich in oberer linker Ecke einfügen
            InkStroke topLeft = builder.CreateStroke(new List<Point>() {
                new Point(1, 1),
                new Point(2, 2) });
            container.AddStroke(topLeft);

            // Strich in unterer Rechter Ecke einfügen
            InkStroke bottomRight = builder.CreateStroke(new List<Point>() {
                new Point(imgRect.Width -2, imgRect.Height -2),
                new Point(imgRect.Width -1, imgRect.Height -1) });   
            container.AddStroke(bottomRight);

            // Striche in WriteableBitmap speichern
            WriteableBitmap bmp;
            using (InMemoryRandomAccessStream ims =
                new InMemoryRandomAccessStream())
            {
                await container.SaveAsync(ims);
                bmp = await new WriteableBitmap(1, 1)
                    .FromStream(ims, BitmapPixelFormat.Bgra8);
            }
            // Bilder zusammenfügen
            b.Blit(imgRect, bmp, imgRect, WriteableBitmapExtensions.BlendMode.Alpha);
        }
コード例 #2
0
        private async void LoadWallpaperArt()
        {
            if (_loaded ||
                !App.Locator.AppSettingsHelper.Read("WallpaperArt", true, SettingsStrategy.Roaming)) return;

            var wait = App.Locator.AppSettingsHelper.Read<int>("WallpaperDayWait");
            var created = App.Locator.AppSettingsHelper.ReadJsonAs<DateTime>("WallpaperCreated");

            // Set the image brush
            var imageBrush = new ImageBrush { Opacity = .25, Stretch = Stretch.UniformToFill, AlignmentY = AlignmentY.Top};
            LayoutGrid.Background = imageBrush;

            // Once a week remake the wallpaper
            if ((DateTime.Now - created).TotalDays > wait)
            {
                var albums =
                    App.Locator.CollectionService.Albums.ToList()
                        .Where(p => p.HasArtwork)
                        .ToList();

                var albumCount = albums.Count;

                if (albumCount < 10) return;


                var h = Window.Current.Bounds.Height;
                var rows = (int) Math.Ceiling(h/(ActualWidth/5));
                const int collumns = 5;

                var albumSize = (int) Window.Current.Bounds.Width/collumns;

                var numImages = rows*5;
                var imagesNeeded = numImages - albumCount;

                var shuffle = await Task.FromResult(albums
                    .Shuffle()
                    .Take(numImages > albumCount ? albumCount : numImages)
                    .ToList());

                if (imagesNeeded > 0)
                {
                    var repeatList = new List<Album>();

                    while (imagesNeeded > 0)
                    {
                        var takeAmmount = imagesNeeded > albumCount ? albumCount : imagesNeeded;

                        await Task.Run(() => repeatList.AddRange(shuffle.Shuffle().Take(takeAmmount)));

                        imagesNeeded -= shuffle.Count;
                    }

                    shuffle.AddRange(repeatList);
                }

                // Initialize an empty WriteableBitmap.
                var destination = new WriteableBitmap((int) Window.Current.Bounds.Width,
                    (int) Window.Current.Bounds.Height);
                var col = 0; // Current Column Position
                var row = 0; // Current Row Position
                destination.Clear(Colors.Black); // Set the background color of the image to black

                // will be copied
                foreach (var artworkPath in shuffle.Select(album => string.Format(AppConstant.ArtworkPath, album.Id)))
                {
                    var file = await WinRtStorageHelper.GetFileAsync(artworkPath);

                    // Read the image file into a RandomAccessStream
                    using (var fileStream = await file.OpenReadAsync())
                    {
                        try
                        {
                            // Now that you have the raw bytes, create a Image Decoder
                            var decoder = await BitmapDecoder.CreateAsync(fileStream);

                            // Get the first frame from the decoder because we are picking an image
                            var frame = await decoder.GetFrameAsync(0);

                            // Convert the frame into pixels
                            var pixelProvider = await frame.GetPixelDataAsync();

                            // Convert pixels into byte array
                            var srcPixels = pixelProvider.DetachPixelData();
                            var wid = (int) frame.PixelWidth;
                            var hgt = (int) frame.PixelHeight;
                            // Create an in memory WriteableBitmap of the same size
                            var bitmap = new WriteableBitmap(wid, hgt); // Temporary bitmap into which the source

                            using (var pixelStream = bitmap.PixelBuffer.AsStream())
                            {
                                pixelStream.Seek(0, SeekOrigin.Begin);
                                // Push the pixels from the original file into the in-memory bitmap
                                await pixelStream.WriteAsync(srcPixels, 0, srcPixels.Length);
                                bitmap.Invalidate();

                                // Resize the in-memory bitmap and Blit (paste) it at the correct tile
                                // position (row, col)
                                destination.Blit(new Rect(col*albumSize, row*albumSize, albumSize, albumSize),
                                    bitmap.Resize(albumSize, albumSize, WriteableBitmapExtensions.Interpolation.Bilinear),
                                    new Rect(0, 0, albumSize, albumSize));
                                col++;
                                if (col < collumns) continue;

                                row++;
                                col = 0;
                            }
                        }
                        catch
                        {
                            // ignored
                        }
                    }
                }

                var wallpaper =
                    await WinRtStorageHelper.CreateFileAsync("wallpaper.jpg", ApplicationData.Current.LocalFolder);
                using (var rndWrite = await wallpaper.OpenAsync(FileAccessMode.ReadWrite))
                {
                    await destination.ToStreamAsJpeg(rndWrite);
                }

                App.Locator.AppSettingsHelper.WriteAsJson("WallpaperCreated", DateTime.Now);
                // If there are 30 or less albums then recreate in one day, else wait a week
                App.Locator.AppSettingsHelper.Write("WallpaperDayWait", albums.Count < 30 ? 1 : 7);

                imageBrush.ImageSource = null;
                imageBrush.ImageSource = new BitmapImage(new Uri("ms-appdata:/local/wallpaper.jpg"));
            }
            else if (created != DateTime.MinValue)
            {
                // Not the first time, so there must already be one created
                imageBrush.ImageSource = new BitmapImage(new Uri("ms-appdata:/local/wallpaper.jpg"));
            }

            _loaded = true;
        }
コード例 #3
0
        async Task CreateCollage(IReadOnlyList<StorageFile> files)
        {
            progressIndicator.Visibility = Windows.UI.Xaml.Visibility.Visible;
            var sampleDataGroups = files;
            if (sampleDataGroups.Count() == 0) return;

            try
            {
                // Do a square-root of the number of images to get the
                // number of images on x and y axis
                int number = (int)Math.Ceiling(Math.Sqrt((double)files.Count));
                // Calculate the width of each small image in the collage
                int numberX = (int)(ImageCollage.ActualWidth / number);
                int numberY = (int)(ImageCollage.ActualHeight / number);
                // Initialize an empty WriteableBitmap.
                WriteableBitmap destination = new WriteableBitmap(numberX * number, numberY * number);
                int col = 0; // Current Column Position
                int row = 0; // Current Row Position
                destination.Clear(Colors.White); // Set the background color of the image to white
                WriteableBitmap bitmap; // Temporary bitmap into which the source
                // will be copied
                foreach (var file in files)
                {
                    // Create RandomAccessStream reference from the current selected image
                    RandomAccessStreamReference streamRef = RandomAccessStreamReference.CreateFromFile(file);
                    int wid = 0;
                    int hgt = 0;
                    byte[] srcPixels;
                    // Read the image file into a RandomAccessStream
                    using (IRandomAccessStreamWithContentType fileStream = await streamRef.OpenReadAsync())
                    {
                        // Now that you have the raw bytes, create a Image Decoder
                        BitmapDecoder decoder = await BitmapDecoder.CreateAsync(fileStream);
                        // Get the first frame from the decoder because we are picking an image
                        BitmapFrame frame = await decoder.GetFrameAsync(0);
                        // Convert the frame into pixels
                        PixelDataProvider pixelProvider = await frame.GetPixelDataAsync();
                        // Convert pixels into byte array
                        srcPixels = pixelProvider.DetachPixelData();
                        wid = (int)frame.PixelWidth;
                        hgt = (int)frame.PixelHeight;
                        // Create an in memory WriteableBitmap of the same size
                        bitmap = new WriteableBitmap(wid, hgt);
                        Stream pixelStream = bitmap.PixelBuffer.AsStream();
                        pixelStream.Seek(0, SeekOrigin.Begin);
                        // Push the pixels from the original file into the in-memory bitmap
                        pixelStream.Write(srcPixels, 0, (int)srcPixels.Length);
                        bitmap.Invalidate();

                        if (row < number)
                        {
                            // Resize the in-memory bitmap and Blit (paste) it at the correct tile
                            // position (row, col)
                            destination.Blit(new Rect(col * numberX, row * numberY, numberX, numberY),
                                bitmap.Resize(numberX, numberY, WriteableBitmapExtensions.Interpolation.Bilinear),
                                new Rect(0, 0, numberX, numberY));
                            col++;
                            if (col >= number)
                            {
                                row++;
                                col = 0;
                            }
                        }
                    }
                }

                ImageCollage.Source = destination;
                ((WriteableBitmap)ImageCollage.Source).Invalidate();
                progressIndicator.Visibility = Windows.UI.Xaml.Visibility.Collapsed;
            }
            catch (Exception ex)
            {
                // TODO: Log Error, unable to render image
                throw;
            }
        }
コード例 #4
0
        private async Task ResizeReferenceImage()
        {
            this.Precentage = 0.0D;

            ToolControlsVisibility = Visibility.Visible;

            await DispatcherHelper.RunAsync(async () =>
            {
                try
                {
                    OnStarted();

                    var entries = Enum.GetValues(typeof (VisualAssets));
                    var count = entries.Length;
                    var percentagePerResizeCycle = 100/count;

                    StorageFolder fld = null;

                    if (!string.IsNullOrEmpty(OutputDirectory) || !string.IsNullOrWhiteSpace(OutputDirectory))
                    {
                        fld = await StorageFolder.GetFolderFromPathAsync(OutputDirectory);
                    }

                    if (ReferenceImage != null)
                    {
                        foreach (VisualAssets vasset in entries)
                        {
                            CurrentFileName = OutputDirectory + Enum.GetName(typeof (VisualAssets), vasset) + ".png";

                            //Set the current cycle
                            Precentage += percentagePerResizeCycle;


                            var currentImageData = EnumTools.GetAttribute<ImageDataAttribute>(vasset);

                            WriteableBitmap imgCopy = ReferenceImage.Clone();


                            var resizedImage = imgCopy.Resize(currentImageData.IconicWidth,
                                currentImageData.IconicHeight,
                                WriteableBitmapExtensions.Interpolation.Bilinear);

                            var visualAsset = new WriteableBitmap(currentImageData.Width, currentImageData.Height);


                            var outerWidth = visualAsset.PixelWidth/2;
                            var outerHeight = visualAsset.PixelHeight/2;

                            var innerWidth = resizedImage.PixelWidth/2;
                            var innerHeight = resizedImage.PixelHeight/2;

                            var placmentPointWidht = outerWidth - innerWidth;
                            var placmentPointHeight = outerHeight - innerHeight;

                            visualAsset.Blit(new Point(placmentPointWidht, placmentPointHeight), resizedImage,
                                new Rect(0, 0, resizedImage.PixelWidth, resizedImage.PixelHeight), Colors.White,
                                WriteableBitmapExtensions.BlendMode.Alpha);


                            IRandomAccessStream stream = new InMemoryRandomAccessStream();


                            var bytes = visualAsset.PixelBuffer.ToArray();

                            var assetName = "";

                            if (Enum.GetName(typeof (VisualAssets), vasset).Contains("altform"))
                            {
                                assetName = Enum.GetName(typeof (VisualAssets), vasset)
                                    .Replace("_altform", "_altform-unplated.png").Replace("TargetSize",".targetsize-");
                            }
                            else
                            {
                                assetName = Enum.GetName(typeof (VisualAssets), vasset)
                                    .Replace("Scale", ".scale-")
                                    .Replace("Square", "")
                                    .Replace("Wide", "") +
                                            (ChosenTheme == ThemeChosen.Dark ? "_black.png" : "_white.png");
                            }

                            using (
                                var imageStream =
                                    await
                                        fld.OpenStreamForWriteAsync(assetName
                                            ,
                                            CreationCollisionOption.ReplaceExisting))
                            {
                                BitmapEncoder enc =
                                    await
                                        BitmapEncoder.CreateAsync(BitmapEncoder.PngEncoderId,
                                            imageStream.AsRandomAccessStream());
                                enc.SetPixelData(BitmapPixelFormat.Bgra8,
                                    BitmapAlphaMode.Straight,
                                    (uint) visualAsset.PixelWidth,
                                    (uint) visualAsset.PixelHeight,
                                    96, 96,
                                    visualAsset.PixelBuffer.ToArray());

                                await enc.FlushAsync();
                            }
                        }

                        Precentage = 100;
                        RaisePropertyChanged(() => Precentage);

                        await Task.Delay(300);

                        ToolControlsVisibility = Visibility.Collapsed;
                        ChooseThemeVisibility = Visibility.Collapsed;
                        
                        OnEnded();

                        var messageDialog = new MessageDialog("Asset Creation successfully finished.");

                        await messageDialog.ShowAsync();

                    }
                }
                catch (Exception)
                {
                    var messageDialog =
                        new MessageDialog(
                            "Sorry, but you have to choose a folder within your pictures library. Thank you.");
                    await messageDialog.ShowAsync();
                }
            });
        }
コード例 #5
0
        async Task CreateCollage()
        {
            var sampleDataGroups = this._allGroups;
            if (sampleDataGroups.Count() > 0 && sampleDataGroups.ToList()[0].TopItems.Count() == 0) return;
            List<TwitterList> list = sampleDataGroups.ToList();

            foreach (var currentList in list)
            {
                try
                {
                    IEnumerable<TweetItem> topItems = currentList.TopItems;

                    List<Uri> uris = (from tweetItem in topItems
                                      select ((BitmapImage)tweetItem.Image).UriSource).ToList<Uri>();

                    if (uris.Count > 0)
                    {
                        int number = (int)Math.Ceiling(Math.Sqrt((double)uris.Count));
                        WriteableBitmap destination = new WriteableBitmap(48 * number, 48 * number);
                        int col = 0;
                        int row = 0;
                        destination.Clear(Colors.Transparent);
                        WriteableBitmap bitmap;
                        foreach (var uri1 in uris)
                        {
                            RandomAccessStreamReference streamRef = RandomAccessStreamReference.CreateFromUri(uri1);
                            int wid = 0;
                            int hgt = 0;
                            byte[] srcPixels;
                            using (IRandomAccessStreamWithContentType fileStream = await streamRef.OpenReadAsync())
                            {
                                BitmapDecoder decoder = await BitmapDecoder.CreateAsync(fileStream);
                                BitmapFrame frame = await decoder.GetFrameAsync(0);
                                PixelDataProvider pixelProvider = await frame.GetPixelDataAsync();
                                srcPixels = pixelProvider.DetachPixelData();
                                wid = (int)frame.PixelWidth;
                                hgt = (int)frame.PixelHeight;
                                bitmap = new WriteableBitmap(wid, hgt);
                            }
                            Stream pixelStream1 = bitmap.PixelBuffer.AsStream();

                            pixelStream1.Seek(0, SeekOrigin.Begin);
                            pixelStream1.Write(srcPixels, 0, (int)srcPixels.Length);
                            bitmap.Invalidate();

                            if (row < number)
                            {
                                destination.Blit(new Rect(col * wid, row * hgt, wid, hgt), bitmap, new Rect(0, 0, wid, hgt));
                                col++;
                                if (col >= number)
                                {
                                    row++;
                                    col = 0;
                                }
                            }
                        }
                        currentList.Image = destination;
                        ((WriteableBitmap)currentList.Image).Invalidate();
                    }

                }
                catch (Exception ex)
                {
                    // TODO: Log Error, unable to render image
                }
            }
        }
コード例 #6
0
ファイル: WriteableImage.cs プロジェクト: uwe-e/BSE.Tunes
        private async Task<BitmapSource> GetWriteableBitmap()
        {
            var width = (int)this.Width;
            var height = width;
            WriteableBitmap writeableBitmap = null;
            string cacheFileName = string.Format("{0}.{1}", this.CacheName, ImageExtension);
            var storageFile = await Windows.Storage.ApplicationData.Current.LocalFolder.TryGetItemAsync(cacheFileName) as StorageFile;
            if (storageFile != null)
            {
                writeableBitmap = await new WriteableBitmap(width, height).LoadAsync(storageFile);
            }
            else
            {
                try
                {
                    var innerWidth = width / 2;
                    var innerHeight = innerWidth;
                    writeableBitmap = new WriteableBitmap(width, height);
                    int index = 0;
                    foreach (Uri uri in this.m_uriCollection)
                    {
                        try
                        {
                            var randomAccessStreamReference = RandomAccessStreamReference.CreateFromUri(uri);
                            using (IRandomAccessStream randomAccessStream = await randomAccessStreamReference.OpenReadAsync())
                            {
                                if (randomAccessStream != null)
                                {
                                    //We initialize the bitmap with height and width, but the actual size will be reset after the FromStream method!
                                    WriteableBitmap innerImage = new WriteableBitmap(innerWidth, innerHeight);
                                    innerImage = await innerImage.FromStream(randomAccessStream);

                                    int xPosition = 0;
                                    int yPosition = 0;

                                    if (index == 1 || index == 2)
                                    {
                                        xPosition = xPosition + innerWidth;
                                    }
                                    if (index == 2 || index == 3)
                                    {
                                        yPosition = yPosition + innerHeight;
                                    }

                                    writeableBitmap.Blit(
                                        new Rect()
                                        {
                                            Height = innerHeight,
                                            Width = innerWidth,
                                            X = xPosition,
                                            Y = yPosition
                                        },
                                            innerImage,
                                            new Rect()
                                            {
                                                Height = innerImage.PixelHeight,
                                                Width = innerImage.PixelWidth,
                                                X = 0,
                                                Y = 0
                                            }, WriteableBitmapExtensions.BlendMode.Additive);
                                }
                                index++;
                            }
                        }
                        catch(Exception)
                        { }
                    }
                    await writeableBitmap.SaveToFile(Windows.Storage.ApplicationData.Current.LocalFolder, cacheFileName, CreationCollisionOption.ReplaceExisting);
                }
                catch (Exception)
                {
                }
            }
            return writeableBitmap;
        }
コード例 #7
0
		public async Task<BitmapSource> GetBitmapSource(object bitmapSource, string cacheName, int width, bool asThumbnail = false)
		{
			var height = width;
			WriteableBitmap writeableBitmap = null;
			ObservableCollection<Uri> uriSource = bitmapSource as ObservableCollection<Uri>;
			if (!string.IsNullOrEmpty(cacheName) && uriSource != null)
			{
				try
				{
					cacheName = asThumbnail ? cacheName + ThumbnailPart : cacheName;
					string cacheFileName = string.Format("{0}.{1}", cacheName, ImageExtension);
					var storageFolder = await LocalStorage.GetImageFolderAsync();
					var storageFile = await storageFolder.TryGetItemAsync(cacheFileName) as StorageFile;
					if (storageFile != null)
					{
						writeableBitmap = await new WriteableBitmap(width, height).LoadAsync(storageFile);
					}

					var innerWidth = width / 2;
					var innerHeight = innerWidth;
					writeableBitmap = new WriteableBitmap(width, height);
					int index = 0;
					foreach (Uri uri in uriSource)
					{
						try
						{
							var randomAccessStreamReference = RandomAccessStreamReference.CreateFromUri(uri);
							using (IRandomAccessStream randomAccessStream = await randomAccessStreamReference.OpenReadAsync())
							{
								if (randomAccessStream != null)
								{
									//We initialize the bitmap with height and width, but the actual size will be reset after the FromStream method!
									WriteableBitmap innerImage = new WriteableBitmap(innerWidth, innerHeight);
									innerImage = await innerImage.FromStream(randomAccessStream);

									int xPosition = 0;
									int yPosition = 0;

									if (index == 1 || index == 2)
									{
										xPosition = xPosition + innerWidth;
									}
									if (index == 1 || index == 3)
									{
										yPosition = yPosition + innerHeight;
									}

									writeableBitmap.Blit(
										new Rect()
										{
											Height = innerHeight,
											Width = innerWidth,
											X = xPosition,
											Y = yPosition
										},
											innerImage,
											new Rect()
											{
												Height = innerImage.PixelHeight,
												Width = innerImage.PixelWidth,
												X = 0,
												Y = 0
											}, WriteableBitmapExtensions.BlendMode.Additive);
								}
								index++;
							}
						}
						catch (Exception)
						{ }
					}
					await writeableBitmap.SaveToFile(storageFolder, cacheFileName, CreationCollisionOption.ReplaceExisting);
				}
				catch (Exception)
				{
				}
			}
			return writeableBitmap;
		}