Skip to content

Commit

Permalink
Can save collage locally (and decide not to upload to the web)
Browse files Browse the repository at this point in the history
  • Loading branch information
SHOEGAZEssb committed Jan 16, 2018
1 parent f23e874 commit 9c8b7d6
Show file tree
Hide file tree
Showing 2 changed files with 126 additions and 21 deletions.
@@ -1,6 +1,7 @@
using IF.Lastfm.Core.Api.Enums;
using IF.Lastfm.Core.Objects;
using Last.fm_Scrubbler_WPF.Views.ExtraFunctions;
using Microsoft.Win32;
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
Expand Down Expand Up @@ -151,6 +152,35 @@ public bool ShowPlaycounts
}
private bool _showPlaycounts;

/// <summary>
/// If enabled, the image gets uploaded to an
/// image upload service after it is created.
/// </summary>
public bool UploadToWeb
{
get { return _uploadImage; }
set
{
_uploadImage = value;
NotifyOfPropertyChange();
}
}
private bool _uploadImage;

/// <summary>
/// The created collage.
/// </summary>
public BitmapSource Collage
{
get { return _collage; }
private set
{
_collage = value;
NotifyOfPropertyChange();
}
}
private BitmapSource _collage;

/// <summary>
/// Gets if certain controls on the ui are enabled.
/// </summary>
Expand All @@ -176,6 +206,7 @@ public CollageCreatorViewModel()
SelectedCollageSize = CollageSize.ThreeByThree;
ShowNames = true;
ShowPlaycounts = true;
UploadToWeb = true;
}

/// <summary>
Expand All @@ -187,9 +218,10 @@ public async void CreateCollage()

try
{
Collage = null;

int numCollageItems = (int)SelectedCollageSize * (int)SelectedCollageSize;
PngBitmapEncoder collage = null;

if (SelectedCollageType == CollageType.Artists)
{
OnStatusUpdated("Fetching top artists...");
Expand All @@ -199,17 +231,25 @@ public async void CreateCollage()
else
OnStatusUpdated("Error while fetching top artists");
}
else if(SelectedCollageType == CollageType.Albums)
else if (SelectedCollageType == CollageType.Albums)
{
OnStatusUpdated("Fetching top albums...");
var response = await MainViewModel.Client.User.GetTopAlbums(Username, TimeSpan, 1, numCollageItems);
if(response.Success)
if (response.Success)
collage = await StitchImagesTogether(response.Content.Select(a => new Tuple<Uri, string>(a.Images.ExtraLarge, CreateAlbumText(a))).ToList());
else
OnStatusUpdated("Error while fetching top albums");
}

await UploadImage(collage);
using (MemoryStream ms = new MemoryStream())
{
collage.Save(ms);
ConvertToBitmapImage(ms);

if(UploadToWeb)
await UploadImage(ms);
};

OnStatusUpdated("Successfully created collage");
}
catch (Exception ex)
Expand All @@ -222,6 +262,47 @@ public async void CreateCollage()
}
}

/// <summary>
/// Shows a dialog to save the <see cref="Collage"/> to file.
/// </summary>
public void SaveImage()
{
try
{
SaveFileDialog sfd = new SaveFileDialog() { Filter = "Bitmap Image (.bmp) | *.bmp" };
if (sfd.ShowDialog().Value)
{
using (var fileStream = new FileStream(sfd.FileName, FileMode.Create))
{
BitmapEncoder encoder = new PngBitmapEncoder();
encoder.Frames.Add(BitmapFrame.Create(Collage));
encoder.Save(fileStream);
}
}
}
catch(Exception ex)
{
OnStatusUpdated("Fatal error while saving collage to file: " + ex.Message);
}
}

/// <summary>
/// Converts the collage to a display-able image.
/// </summary>
/// <param name="ms">MemoryStream containing the image.</param>
private void ConvertToBitmapImage(MemoryStream ms)
{
var bitmapImage = new BitmapImage();

ms.Seek(0, SeekOrigin.Begin);
bitmapImage.BeginInit();
bitmapImage.CacheOption = BitmapCacheOption.OnLoad;
bitmapImage.StreamSource = ms;
bitmapImage.EndInit();

Collage = bitmapImage;
}

/// <summary>
/// Creates the text for the <see cref="CollageType.Artists"/>.
/// </summary>
Expand Down Expand Up @@ -323,34 +404,31 @@ private async Task<PngBitmapEncoder> StitchImagesTogether(List<Tuple<Uri, string
/// <summary>
/// Uploads the image to imgur.
/// </summary>
/// <param name="encoder">Encoder containing the stitched image.</param>
/// <param name="ms">MemoryStream containing the image.</param>
/// <returns>Task.</returns>
private async Task UploadImage(PngBitmapEncoder encoder)
private async Task UploadImage(MemoryStream ms)
{
OnStatusUpdated("Uploading image...");
using (var w = new WebClient())
{
w.Proxy = null;
w.Headers.Add("Authorization", "Client-ID " + "80dfa34b8899ce5");

using (MemoryStream ms = new MemoryStream())
{
encoder.Save(ms);
var values = new NameValueCollection
var values = new NameValueCollection
{
{ "image", Convert.ToBase64String(ms.ToArray()) },
};

byte[] response = null;
await Task.Run(() => response = w.UploadValues("https://api.imgur.com/3/upload.xml", values));
byte[] response = null;
await Task.Run(() => response = w.UploadValues("https://api.imgur.com/3/upload.xml", values));

using (MemoryStream xMs = new MemoryStream(response))
{
var doc = XDocument.Load(xMs);
string link = doc.Descendants().Where(i => i.Name == "link").FirstOrDefault().Value;
Process.Start(link);
}
using (MemoryStream xMs = new MemoryStream(response))
{
var doc = XDocument.Load(xMs);
string link = doc.Descendants().Where(i => i.Name == "link").FirstOrDefault().Value;
Process.Start(link);
}

}
}
}
Expand Down
33 changes: 30 additions & 3 deletions Last.fm-Scrubbler-WPF/Views/ExtraFunctions/CollageCreatorView.xaml
Expand Up @@ -10,7 +10,7 @@
xmlns:extraFuncVMs="clr-namespace:Last.fm_Scrubbler_WPF.ViewModels.ExtraFunctions"
xmlns:conv="clr-namespace:Last.fm_Scrubbler_WPF.Converters"
mc:Ignorable="d"
d:DesignHeight="60" d:DesignWidth="500">
d:DesignHeight="100" d:DesignWidth="500">

<UserControl.Resources>
<ObjectDataProvider MethodName="GetValues"
Expand Down Expand Up @@ -43,6 +43,10 @@
<RowDefinition Height="Auto"/>
<RowDefinition Height="5"/>
<RowDefinition Height="Auto"/>
<RowDefinition Height="5"/>
<RowDefinition Height="*"/>
<RowDefinition Height="5"/>
<RowDefinition Height="Auto"/>
</Grid.RowDefinitions>

<Grid Grid.Row="0">
Expand Down Expand Up @@ -106,10 +110,33 @@
<ColumnDefinition Width="Auto"/>
<ColumnDefinition Width="5"/>
<ColumnDefinition Width="Auto"/>
<ColumnDefinition Width="5"/>
<ColumnDefinition Width="Auto"/>
</Grid.ColumnDefinitions>

<CheckBox Grid.Row="0" Grid.Column="0" Content="Show Names" IsChecked="{Binding ShowNames}" VerticalAlignment="Center"/>
<CheckBox Grid.Row="0" Grid.Column="2" Content="Show Playcounts" IsChecked="{Binding ShowPlaycounts}" VerticalAlignment="Center"/>
<CheckBox Grid.Row="0" Grid.Column="0" Content="Show Names" IsChecked="{Binding ShowNames}" VerticalAlignment="Center" Style="{StaticResource EnableControlsStyle}"/>
<CheckBox Grid.Row="0" Grid.Column="2" Content="Show Playcounts" IsChecked="{Binding ShowPlaycounts}" VerticalAlignment="Center" Style="{StaticResource EnableControlsStyle}"/>
<CheckBox Grid.Row="0" Grid.Column="4" Content="Upload Image" IsChecked="{Binding UploadToWeb}" VerticalAlignment="Center" Style="{StaticResource EnableControlsStyle}"/>
</Grid>

<Image Grid.Row="4" Grid.Column="0" Source="{Binding Collage}"/>
<Button Grid.Row="6" Grid.Column="0" HorizontalAlignment="Center" Content="Save Image">
<Button.Style>
<Style TargetType="Button" BasedOn="{StaticResource EnableControlsStyle}">
<Setter Property="Visibility" Value="Visible"/>
<Style.Triggers>
<DataTrigger Binding="{Binding Collage}" Value="{x:Null}">
<Setter Property="Visibility" Value="Collapsed"/>
</DataTrigger>
</Style.Triggers>
</Style>
</Button.Style>
<i:Interaction.Triggers>
<i:EventTrigger EventName="Click">
<cal:ActionMessage MethodName="SaveImage"/>
</i:EventTrigger>
</i:Interaction.Triggers>
</Button>

</Grid>
</UserControl>

0 comments on commit 9c8b7d6

Please sign in to comment.