Skip to content

Commit 83a4e06

Browse files
author
Giuseppe Dinardo
committed
Fixed bugs, added feature
- Fixed bugs: 1) Fixed bug where dragging a null file(?) over the imgviewer container made the application crash - Added feature: it is now possible to replace the transparency of a png image when converting it to another format
1 parent b6e12a4 commit 83a4e06

File tree

4 files changed

+138
-68
lines changed

4 files changed

+138
-68
lines changed

ImageConverter/ImageConversionHandler.cs

Lines changed: 98 additions & 32 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,7 @@ public class ImageConversionHandler
2020
private static BmpBitmapEncoder bmpEncoder;
2121
private static GifBitmapEncoder gifEncoder;
2222

23+
private static string tempImgPath = null;
2324
private static string imageName; //name of the image to convert
2425
private static string directoryOfImageToConvert; //directory of the image to convert
2526
private static int color = 0; //color to replace the transparency with
@@ -34,18 +35,18 @@ public static bool IsImage(string pathOfFile)
3435
return false;
3536
}
3637

38+
/// <summary>
39+
/// Starts the conversion of one or more image to the specified format
40+
/// </summary>
41+
/// <param name="format"> format to which convert the image</param>
42+
/// <param name="pathsOfImagesToConvert"> path of the image to convert </param>
43+
/// <param name="gifRepeatTimes"> the times the gif shall repeat: infinite(0)-10 </param>
44+
/// <param name="colorToReplTheTranspWith"> Color to replace the transparency of a png image with</param>
45+
/// <param name="delayTime"> delay between two frames of a gif</param>
46+
/// <returns></returns>
3747
public static async Task<List<bool>> StartConversion(string format, string[] pathsOfImagesToConvert, int gifRepeatTimes, int colorToReplTheTranspWith, int delayTime)
3848
{
39-
if (colorToReplTheTranspWith != 0)
40-
{
41-
MessageBox.Show("Replace transparency not implemented yet", "Error", MessageBoxButton.OK, MessageBoxImage.Error);
42-
var list = new List<bool>();
43-
list.Add(false);
44-
return list;
45-
46-
color = colorToReplTheTranspWith;
47-
}
48-
49+
color = colorToReplTheTranspWith;
4950
conversionsResults = new List<bool>();
5051
foreach (var imageToConvertPath in pathsOfImagesToConvert)
5152
{
@@ -137,16 +138,29 @@ private static async Task<bool> ToJpegOrJpg(string pathOfImage, string format)
137138
using (Stream st = File.OpenRead(pathOfImage))
138139
{
139140
var imageToConv = new BitmapImage();
140-
imageToConv.BeginInit();
141-
imageToConv.StreamSource = st;
142-
imageToConv.CacheOption = BitmapCacheOption.OnLoad;
143-
imageToConv.EndInit();
144-
jpegOrJpgEncoder.Frames.Add(BitmapFrame.Create(imageToConv));
145-
146-
st.Close();
147-
}//loads image to convert from a stream and converts it
141+
if (color != 0)
142+
{
143+
Image imgToConvertImage = Image.FromStream(st);
144+
using (Stream st2 = File.OpenRead(ReplaceTransparency(imgToConvertImage)))
145+
{
146+
imageToConv.BeginInit();
147+
imageToConv.StreamSource = st2;
148+
imageToConv.CacheOption = BitmapCacheOption.OnLoad;
149+
imageToConv.EndInit();
150+
jpegOrJpgEncoder.Frames.Add(BitmapFrame.Create(imageToConv));
151+
}
152+
}//if the user selected a color to convert the image transparency with
153+
else
154+
{
155+
imageToConv.BeginInit();
156+
imageToConv.StreamSource = st;
157+
imageToConv.CacheOption = BitmapCacheOption.OnLoad;
158+
imageToConv.EndInit();
159+
jpegOrJpgEncoder.Frames.Add(BitmapFrame.Create(imageToConv));
160+
}
161+
}//loads image to convert from a stream, eventually replace the transparency, and converts it
148162

149-
#region Saves image based on format(jpeg or jpg) and checks wether it was saved correctly
163+
#region Saves image based on format(jpeg or jpg), eventually deletes temp file, and checks wether it was saved correctly
150164
if (format == "jpeg")
151165
{
152166
using (Stream st = File.Create($"{directoryOfImageToConvert}\\{imageName}.jpeg"))
@@ -164,6 +178,9 @@ private static async Task<bool> ToJpegOrJpg(string pathOfImage, string format)
164178
}
165179
}
166180

181+
if (tempImgPath != null) //deletes the temporary file in the temp folder(the image with the transparency replaced but still not converted)
182+
File.Delete(tempImgPath);
183+
167184
if (File.Exists($"{directoryOfImageToConvert}\\{imageName}.jpeg") || File.Exists($"{directoryOfImageToConvert}\\{imageName}.jpg"))
168185
{
169186
return true;
@@ -185,14 +202,27 @@ private static async Task<bool> ToBmp(string pathOfImage)
185202
using (Stream st = File.OpenRead(pathOfImage))
186203
{
187204
var imageToConv = new BitmapImage();
188-
imageToConv.BeginInit();
189-
imageToConv.StreamSource = st;
190-
imageToConv.CacheOption = BitmapCacheOption.OnLoad;
191-
imageToConv.EndInit();
192-
193-
bmpEncoder.Frames.Add(BitmapFrame.Create(imageToConv));
194-
st.Close();
195-
}//loads image to convert from a stream and converts it
205+
if (color != 0)
206+
{
207+
Image imgToConvertImage = Image.FromStream(st);
208+
using (Stream st2 = File.OpenRead(ReplaceTransparency(imgToConvertImage)))
209+
{
210+
imageToConv.BeginInit();
211+
imageToConv.StreamSource = st2;
212+
imageToConv.CacheOption = BitmapCacheOption.OnLoad;
213+
imageToConv.EndInit();
214+
bmpEncoder.Frames.Add(BitmapFrame.Create(imageToConv));
215+
}
216+
}//if the user selected a color to convert the image transparency with
217+
else
218+
{
219+
imageToConv.BeginInit();
220+
imageToConv.StreamSource = st;
221+
imageToConv.CacheOption = BitmapCacheOption.OnLoad;
222+
imageToConv.EndInit();
223+
bmpEncoder.Frames.Add(BitmapFrame.Create(imageToConv));
224+
}
225+
}//loads image to convert from a stream, eventually replace the transparency, and converts it
196226

197227
#region saves bmp image and checkes whether it was saved correctly
198228
using (Stream st = File.Create($"{directoryOfImageToConvert}\\{imageName}.bmp"))
@@ -249,7 +279,7 @@ private static async Task<bool> ImagesToGif(string[] imagesPaths, int repeatTime
249279
int a = 1;
250280
for (int i = 0; i < fileBytesList.Count; i++)
251281
{
252-
if(fileBytesList[i] == 44 && fileBytesList[i+1] == 0 && fileBytesList[i+2] == 0 && fileBytesList[i+3] == 0 && fileBytesList[i+4] == 0)
282+
if (fileBytesList[i] == 44 && fileBytesList[i + 1] == 0 && fileBytesList[i + 2] == 0 && fileBytesList[i + 3] == 0 && fileBytesList[i + 4] == 0)
253283
{
254284
System.Diagnostics.Debug.WriteLine($"Found start of image descriptor block at index: {i}.\nImage descriptor n°{a}");
255285
fileBytesList.InsertRange(i, graphicExtension);
@@ -282,7 +312,7 @@ private static async Task<bool> ImagesToGif(string[] imagesPaths, int repeatTime
282312
} //otherwise: return false
283313
}
284314

285-
private static async Task<bool> ToIconOrCur(string imgToConvertPath, string format)
315+
private static async Task<bool> ToIconOrCur(string imgToConvertPath, string format) //TODO: Fix conversion of bmp images to ico or cur
286316
{
287317
var ext = Path.GetExtension(imgToConvertPath).ToLower();
288318
#region if the image to convert isn't a png or bmp image it can't be converterd: return null
@@ -348,7 +378,18 @@ private static async Task<bool> ToIconOrCur(string imgToConvertPath, string form
348378
#endregion
349379
#region Image data
350380
if (ext == ".png")
351-
imgToConvert.Save(memStream, ImageFormat.Png);
381+
{
382+
if (color != 0)
383+
{
384+
using (Stream st = File.OpenRead(ReplaceTransparency(imgToConvert)))
385+
{
386+
var imgToConvWithReplacedTransp = Image.FromStream(st);
387+
imgToConvWithReplacedTransp.Save(memStream, ImageFormat.Png);
388+
}
389+
}//if the user selected a color to convert the image transparency with
390+
else
391+
imgToConvert.Save(memStream, ImageFormat.Png);
392+
}
352393
else
353394
{
354395
byte[] bmpBytes = File.ReadAllBytes(imgToConvertPath);
@@ -406,9 +447,34 @@ private static async Task<bool> ToIconOrCur(string imgToConvertPath, string form
406447
#endregion
407448
}
408449

409-
private static async Task<BitmapImage> ReplaceTransparency(Image img)
450+
private static string ReplaceTransparency(Image img)
410451
{
411-
return new BitmapImage();
452+
Bitmap imgWithTranspReplaced = new Bitmap(img.Width, img.Height);
453+
Graphics g = Graphics.FromImage(imgWithTranspReplaced);
454+
455+
if (color == 1)
456+
{
457+
g.Clear(Color.White);
458+
}//replace transparency with white
459+
else
460+
{
461+
g.Clear(Color.Black);
462+
}//replace transparency with black
463+
g.DrawImage(img, 0, 0);
464+
465+
string tempPath = Path.GetTempPath();
466+
467+
#region Creates folder of ImageConverter in temp folder, saves imgWithTranspReplaced in it and returns its path
468+
if (!Directory.Exists($"{tempPath}\\ImageConverter")) //if the temp folder of ImageConverter doesn't exist create it
469+
Directory.CreateDirectory($"{tempPath}\\ImageConverter");
470+
471+
imgWithTranspReplaced.Save($"{tempPath}\\ImageConverter\\tempImgWithTranspReplaced.png"); //save image, return its path and dispose objects
472+
tempImgPath = $"{tempPath}\\ImageConverter\\tempImgWithTranspReplaced.png";
473+
imgWithTranspReplaced.Dispose();
474+
g.Dispose();
475+
476+
return tempImgPath;
477+
#endregion
412478
}
413479
}
414480
}

ImageConverter/ImageConverter.csproj

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -221,5 +221,8 @@
221221
<Resource Include="TestImages\PngImages\simpsons_PNG95.png" />
222222
<Resource Include="TestImages\PngImages\smp_badge1-500x500.png" />
223223
</ItemGroup>
224+
<ItemGroup>
225+
<Folder Include="Temp\" />
226+
</ItemGroup>
224227
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
225228
</Project>

ImageConverter/MainWindow.xaml

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -34,7 +34,7 @@
3434
</ComboBox>
3535

3636
<!-- GIF format options-->
37-
<StackPanel x:Name="GifOptionsSP" Orientation="Vertical" Margin="470,190,165,256" Visibility="Hidden">
37+
<StackPanel x:Name="GifOptionsSP" Orientation="Vertical" Margin="470,202,165,244" Visibility="Hidden">
3838
<!-- Option that indicates how many times the gif shall be repeated -->
3939
<StackPanel Orientation="Horizontal">
4040
<Label x:Name="GifRepeatTimes" Content="Volte che la gif si ripeterà:"/>
@@ -52,7 +52,7 @@
5252
<Label Content="10"/>
5353
</ComboBox>
5454
</StackPanel>
55-
55+
5656
<!-- Option that indicates the delay between frames-->
5757
<StackPanel Orientation="Horizontal" Height="26">
5858
<Label Content="Tempo di passaggio da un frame all'altro:" x:Name="DelayTimeLabel" />
@@ -68,7 +68,7 @@
6868
</StackPanel>
6969

7070
<!-- IMG to convert is PNG: Stackpanel that is shown only when one or more images to convert are pngs, it indicates the color the transparency is going to be replaced with-->
71-
<StackPanel x:Name="ReplaceTransparencySP" Orientation="Horizontal" Width="400" Margin="463,205,91,263" Visibility="Hidden">
71+
<StackPanel x:Name="ReplaceTransparencySP" Orientation="Horizontal" Margin="468,165,107,303" Visibility="Hidden">
7272
<Label Content="Sostituisci la trasparenza della png con: " HorizontalAlignment="Center" VerticalAlignment="Center"/>
7373
<ComboBox x:Name="ReplTranspColCB" HorizontalAlignment="Center" VerticalAlignment="Center" Width="68" SelectedIndex="0" DropDownClosed="ReplTranspColCB_DropDownClosed">
7474
<Label Content="Niente"/>

ImageConverter/MainWindow.xaml.cs

Lines changed: 34 additions & 33 deletions
Original file line numberDiff line numberDiff line change
@@ -83,13 +83,16 @@ private void MainWindow1_Loaded(object sender, RoutedEventArgs e)
8383

8484
private void ImgViewer_DragOver(object sender, DragEventArgs e)
8585
{
86-
string[] droppingFiles = e.Data.GetData(DataFormats.FileDrop) as string[]; //se l'utente sta tentando di convertire più di un'immagine
87-
foreach (var file in droppingFiles)
86+
if (e.Data.GetData(DataFormats.FileDrop) != null)
8887
{
89-
if (ImageConversionHandler.IsImage(file) == false)
88+
string[] droppingFiles = e.Data.GetData(DataFormats.FileDrop) as string[]; //se l'utente sta tentando di convertire più di un'immagine
89+
foreach (var file in droppingFiles)
9090
{
91-
WarningLabel.Visibility = Visibility.Visible;
92-
break;
91+
if (ImageConversionHandler.IsImage(file) == false)
92+
{
93+
WarningLabel.Visibility = Visibility.Visible;
94+
break;
95+
}
9396
}
9497
}
9598
}
@@ -101,28 +104,28 @@ private void ImgViewer_DragLeave(object sender, DragEventArgs e)
101104

102105
private void ImgViewer_Drop(object sender, DragEventArgs e)
103106
{
104-
if (WarningLabel.Visibility == Visibility.Visible)
107+
if (e.Data.GetData(DataFormats.FileDrop) != null)
105108
{
106-
WarningLabel.Visibility = Visibility.Hidden;
107-
return;
108-
} //if the warning label IS visible the dropped file is not an image, so ignore the drop(return)
109+
if (WarningLabel.Visibility == Visibility.Visible)
110+
{
111+
WarningLabel.Visibility = Visibility.Hidden;
112+
return;
113+
} //if the warning label IS visible the dropped file is not an image, so ignore the drop(return)
109114

110-
#region resets controls
111-
ThemeManager.solidColorBrush = new SolidColorBrush();
112-
ThemeManager.solidColorBrush.Color = ThemeManager.RunningOrStaticConversionLabelColor;
113-
ConversionResultTextBlock.Foreground = ThemeManager.solidColorBrush;
114-
ConversionResultTextBlock.Visibility = Visibility.Hidden;
115-
ImagesNameLabel.Text = string.Empty;
116-
if(FormatComboBox.SelectedValue?.ToString() != "System.Windows.Controls.Label: GIF")
117-
{
118-
GifOptionsSP.Visibility = Visibility.Hidden;
119-
}
120-
ReplaceTransparencySP.Visibility = Visibility.Hidden;
121-
#endregion
115+
#region resets controls
116+
ThemeManager.solidColorBrush = new SolidColorBrush();
117+
ThemeManager.solidColorBrush.Color = ThemeManager.RunningOrStaticConversionLabelColor;
118+
ConversionResultTextBlock.Foreground = ThemeManager.solidColorBrush;
119+
ConversionResultTextBlock.Visibility = Visibility.Hidden;
120+
ImagesNameLabel.Text = string.Empty;
121+
if (FormatComboBox.SelectedValue?.ToString() != "System.Windows.Controls.Label: GIF")
122+
{
123+
GifOptionsSP.Visibility = Visibility.Hidden;
124+
}
125+
ReplaceTransparencySP.Visibility = Visibility.Hidden;
126+
#endregion
122127

123-
droppedImages = e.Data.GetData(DataFormats.FileDrop) as string[];
124-
if (e.Data.GetData(DataFormats.FileDrop) != null)
125-
{
128+
droppedImages = e.Data.GetData(DataFormats.FileDrop) as string[];
126129
if (WarningLabel.Visibility == Visibility.Visible)
127130
{
128131
WarningLabel.Visibility = Visibility.Hidden;
@@ -158,7 +161,7 @@ private void ImgViewer_Drop(object sender, DragEventArgs e)
158161
ImgViewer.Source = imageToShow;
159162
st.Close();
160163
} //loads image to show from a stream and shows it, if the image was used directly it would've
161-
//remained in use even after emptying the ImgViewer and so couldn't be deleted
164+
//remained in use even after emptying the ImgViewer and so couldn't be deleted
162165
WarningLabel.Visibility = Visibility.Hidden; //hides the warning label in case it the user tried to convert a non valid file but then dropped a valid file
163166
ConvertImgBttn.IsEnabled = true;
164167
}
@@ -179,10 +182,11 @@ private async void ConvertRoundBttn_MouseDown(object sender, MouseButtonEventArg
179182
return;
180183
} //if a format hasn't been selected prompt user to select one and return
181184

185+
ConversionResultTextBlock.Visibility = Visibility.Hidden; //necessary because if the user converts one image two times in a row it would seem like the conversion didn't start
182186
finishedConversions = new List<bool>();
183187
string selectedFormat = ((FormatComboBox.SelectedItem as System.Windows.Controls.Label).Content as string).ToLower(); //takes the selected format
184188
ThemeManager.solidColorBrush.Color = ThemeManager.RunningOrStaticConversionLabelColor;
185-
ConversionResultTextBlock.Foreground = ThemeManager.solidColorBrush; //se
189+
ConversionResultTextBlock.Foreground = ThemeManager.solidColorBrush; //sets
186190
ConversionResultTextBlock.Visibility = Visibility.Visible; //makes the label of the state of the conversion visible
187191
ConvertImgBttn.IsEnabled = false; //while a conversion is ongoing the convertbttn gets disabled
188192
if (Settings.Default.Language == "it")
@@ -256,7 +260,7 @@ private void FormatComboBox_DropDownClosed(object sender, System.EventArgs e)
256260
{
257261
var selectedValue = (((ComboBox)sender).SelectedItem as Label)?.Content.ToString();
258262

259-
if (selectedValue == "GIF")
263+
if (selectedValue == "GIF")
260264
GifOptionsSP.Visibility = Visibility.Visible;
261265
else
262266
GifOptionsSP.Visibility = Visibility.Hidden;
@@ -265,21 +269,18 @@ private void FormatComboBox_DropDownClosed(object sender, System.EventArgs e)
265269
private void ReplTranspColCB_DropDownClosed(object sender, EventArgs e)
266270
{
267271
var selectedIndex = ((ComboBox)sender).SelectedIndex;
268-
if (selectedIndex == 0)
269-
replTranspWithCol = 0;
270-
else
271-
replTranspWithCol = selectedIndex;
272+
replTranspWithCol = selectedIndex;
272273
}
273274

274275
private void GifRepTimesCB_DropDownClosed_1(object sender, EventArgs e)
275276
{
276277
var selectedValue = (((ComboBox)sender).SelectedItem as Label)?.Content.ToString();
277-
if(selectedValue == "∞")
278+
if (selectedValue == "∞")
278279
{
279280
repGifTimes = 0;
280281
return;
281282
}
282-
repGifTimes = Convert.ToInt32(selectedValue);
283+
repGifTimes = Convert.ToInt32(selectedValue);
283284
}
284285

285286
private void DelayTimesCB_DropDownClosed(object sender, EventArgs e)

0 commit comments

Comments
 (0)