<repo_name>eltoncezar/Album-Art-Folder-Icon<file_sep>/ecr.AlbumFolderIcon/Utils/ImageUtils.cs
﻿//http://jasonjano.wordpress.com/2010/02/13/image-resizing-and-cropping-in-c/
//http://tech.pro/tutorial/620/csharp-tutorial-image-editing-saving-cropping-and-resizing

using System;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
using System.IO;
using System.Linq;
using System.Windows.Media.Imaging;

namespace ecr.AlbumFolderIcon.Utils
{
    public class ImageUtils
    {
        #region Cropping

        //Overload for crop that default starts top left of the image.
        public static System.Drawing.Image CropImage(System.Drawing.Image Image, int Height, int Width)
        {
            return CropImage(Image, Height, Width, 0, 0);
        }

        //The crop image sub
        public static System.Drawing.Image CropImage(System.Drawing.Image Image, int Height, int Width, int StartAtX, int StartAtY)
        {
            Image outimage;
            MemoryStream mm = null;
            try
            {
                //check the image height against our desired image height
                if (Image.Height < Height)
                {
                    Height = Image.Height;
                }
                if (Image.Width < Width)
                {
                    Width = Image.Width;
                }

                //create a bitmap window for cropping
                Bitmap bmPhoto = new Bitmap(Width, Height, PixelFormat.Format24bppRgb);
                bmPhoto.SetResolution(72, 72);

                //create a new graphics object from our image and set properties
                Graphics grPhoto = Graphics.FromImage(bmPhoto);
                grPhoto.SmoothingMode = SmoothingMode.AntiAlias;
                grPhoto.InterpolationMode = InterpolationMode.HighQualityBicubic;
                grPhoto.PixelOffsetMode = PixelOffsetMode.HighQuality;

                //now do the crop
                grPhoto.DrawImage(Image, new Rectangle(0, 0, Width, Height), StartAtX, StartAtY, Width, Height, GraphicsUnit.Pixel);

                // Save out to memory and get an image from it to send back out the method.
                mm = new MemoryStream();
                bmPhoto.Save(mm, System.Drawing.Imaging.ImageFormat.Jpeg);
                Image.Dispose();
                bmPhoto.Dispose();
                grPhoto.Dispose();
                outimage = Image.FromStream(mm);
                return outimage;
            }
            catch (Exception ex)
            {
                throw new Exception("Error cropping image, the error was: " + ex.Message);
            }
        }

        #endregion Cropping

        #region Resizing

        //Hard resize attempts to resize as close as it can to the desired size and then crops the excess
        public static System.Drawing.Image HardResizeImage(int Width, int Height, System.Drawing.Image Image)
        {
            int width = Image.Width;
            int height = Image.Height;
            Image resized = null;
            if (Width > Height)
            {
                resized = ResizeImage(Width, Width, Image);
            }
            else
            {
                resized = ResizeImage(Height, Height, Image);
            }
            Image output = CropImage(resized, Height, Width);

            //return the original resized image
            return output;
        }

        //Image resizing
        public static System.Drawing.Image ResizeImage(int maxWidth, int maxHeight, System.Drawing.Image Image)
        {
            int width = Image.Width;
            int height = Image.Height;
            //if (width > maxWidth || height > maxHeight)
            //{
            //The flips are in here to prevent any embedded image thumbnails -- usually from cameras
            //from displaying as the thumbnail image later, in other words, we want a clean
            //resize, not a grainy one.
            Image.RotateFlip(System.Drawing.RotateFlipType.Rotate180FlipX);
            Image.RotateFlip(System.Drawing.RotateFlipType.Rotate180FlipX);
            float ratio = 0;
            if (width > height)
            {
                ratio = (float)width / (float)height;
                width = maxWidth;
                height = Convert.ToInt32(Math.Round((float)width / ratio));
            }
            else
            {
                ratio = (float)height / (float)width;
                height = maxHeight;
                width = Convert.ToInt32(Math.Round((float)height / ratio));
            }
            //return the resized image
            return Image.GetThumbnailImage(width, height, null, IntPtr.Zero);
            //}
            //return the original resized image
            //return Image;
        }

        #endregion Resizing

        #region Converters

        public static BitmapImage ConvertImageToBitmapImage(Image img)
        {
            // Convert the image in resources to a Stream
            Stream ms = new MemoryStream();
            img.Save(ms, ImageFormat.Png);

            // Create a BitmapImage with the Stream.
            BitmapImage bitmap = new BitmapImage();
            bitmap.BeginInit();
            bitmap.StreamSource = ms;
            bitmap.EndInit();

            return bitmap;
        }

        public static BitmapImage ConvertIconToBitmapImage(Icon icon)
        {
            // Convert the image in resources to a Stream
            Stream ms = new MemoryStream();
            icon.Save(ms);

            // Create a BitmapImage with the Stream.
            BitmapImage bitmap = new BitmapImage();
            bitmap.BeginInit();
            bitmap.StreamSource = ms;
            bitmap.EndInit();

            return bitmap;
        }

        public static BitmapImage ConvertBitmapToBitmapImage(Bitmap bitmap)
        {
            using (MemoryStream memory = new MemoryStream())
            {
                bitmap.Save(memory, ImageFormat.Png);
                memory.Position = 0;
                BitmapImage bitmapImage = new BitmapImage();
                bitmapImage.BeginInit();
                bitmapImage.StreamSource = memory;
                bitmapImage.CacheOption = BitmapCacheOption.OnLoad;
                bitmapImage.EndInit();

                return bitmapImage;
            }
        }

        #endregion Converters
    }
}<file_sep>/README.md
# Album Art Folder Icon

Album Art Folder Icon is a helper to organize your collections of movies/music.
It turns your Windows 7/8 boring folder icons into amazing XP Style folder icons!

![Example](https://raw.githubusercontent.com/eltoncezar/Album-Art-Folder-Icon/master/screenshot.png)

# [Download](https://github.com/eltoncezar/Album-Art-Folder-Icon/releases/download/v1.0/Album.Art.Folder.Icon.exe)
<file_sep>/ecr.AlbumFolderIcon/MainWindow.xaml.cs
﻿using System;
using System.Collections.Specialized;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Forms;
using ecr.AlbumFolderIcon.Core;
using ecr.AlbumFolderIcon.Utils;

namespace ecr.AlbumFolderIcon
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        private StringCollection log = new StringCollection();

        public MainWindow()
        {
            InitializeComponent();

            rtbxErrors.HorizontalScrollBarVisibility = ScrollBarVisibility.Auto;
            rtbxErrors.Document.PageWidth = 1000;
        }

        private void btnSearchPath_Click(object sender, RoutedEventArgs e)
        {
            FolderBrowserDialog dialog = new FolderBrowserDialog();
            DialogResult result = dialog.ShowDialog();

            if (result == System.Windows.Forms.DialogResult.OK)
                txtPath.Text = dialog.SelectedPath;
        }

        private void btnStart_Click(object sender, RoutedEventArgs e)
        {
            //TODO: Insert validation here

            if (!Directory.Exists(txtPath.Text))
            {
                System.Windows.Forms.MessageBox.Show("Directory doesn't exist.");
                return;
            }
            Main(txtPath.Text);
        }

        public void Main(string path)
        {
            DirectoryInfo rootDir = new DirectoryInfo(path);
            WalkDirectoryTree(rootDir);

            // Write out all the files that could not be processed.
            rtbxErrors.AppendText("\r\r Files with error: \r");
            foreach (string s in log)
            {
                rtbxErrors.AppendText(s + "\r");
            }
            rtbxErrors.ScrollToEnd();
        }

        public void WalkDirectoryTree(DirectoryInfo root)
        {
            FileInfo[] files = null;
            DirectoryInfo[] subDirs = null;

            string folderPath = root.FullName + "\\" + txbFileName.Text + txbFileExtension.Text;

            if (File.Exists(folderPath))
            {
                // Update the folder attributes
                DirectoryInfo dir = new DirectoryInfo(root.FullName);
                dir.Attributes = dir.Attributes | FileAttributes.System;

                CreateIcon(folderPath);
                CreateDesktopIni(root.FullName);

                rtbxErrors.AppendText(root.FullName + "\r");
            }

            if (ckbIncludeSubfolders.IsChecked == true)
            {
                // Now find all the subdirectories under this directory.
                subDirs = root.GetDirectories();

                foreach (System.IO.DirectoryInfo dirInfo in subDirs)
                {
                    // Resursive call for each subdirectory.
                    WalkDirectoryTree(dirInfo);
                }
            }
        }

        public void CreateIcon(string path)
        {
            FileInfo file = new FileInfo(path);
            string fileName = file.DirectoryName + "\\folder.ico";

            if (!File.Exists(fileName))
            {
                try
                {
                    System.Drawing.Image src = System.Drawing.Image.FromFile(path);

                    ImageOrientation orientation = src.Height < src.Width ? ImageOrientation.Landscape : ImageOrientation.Portrait;
                    int size = orientation == ImageOrientation.Landscape ? src.Height : src.Width;
                    int sizeToCrop = orientation == ImageOrientation.Landscape ? src.Width - src.Height : src.Height - src.Width;
                    System.Drawing.Image croppedImage = ImageUtils.CropImage(src, size, size, (orientation == ImageOrientation.Landscape ? sizeToCrop / 2 : 0), (orientation == ImageOrientation.Portrait ? sizeToCrop / 2 : 0));
                    System.Drawing.Image resizedImage = ImageUtils.ResizeImage(256, 256, croppedImage);

                    Icon icon = System.Drawing.Icon.FromHandle(new Bitmap(resizedImage).GetHicon());
                    IconEx Iconex = new IconEx(icon);
                    Iconex.Items.RemoveAt(0);

                    // 256x256
                    IconDeviceImage iconDeviceImage = new IconDeviceImage(new System.Drawing.Size(256, 256), System.Windows.Forms.ColorDepth.Depth32Bit);
                    iconDeviceImage.IconImage = new Bitmap(ImageUtils.ResizeImage(256, 256, resizedImage));
                    Iconex.Items.Add(iconDeviceImage);

                    // 48x48
                    iconDeviceImage = new IconDeviceImage(new System.Drawing.Size(48, 48), System.Windows.Forms.ColorDepth.Depth32Bit);
                    iconDeviceImage.IconImage = new Bitmap(ImageUtils.ResizeImage(48, 48, resizedImage));
                    Iconex.Items.Add(iconDeviceImage);

                    // 32x32
                    iconDeviceImage = new IconDeviceImage(new System.Drawing.Size(32, 32), System.Windows.Forms.ColorDepth.Depth32Bit);
                    iconDeviceImage.IconImage = new Bitmap(ImageUtils.ResizeImage(32, 32, resizedImage));
                    Iconex.Items.Add(iconDeviceImage);

                    // 24x24
                    iconDeviceImage = new IconDeviceImage(new System.Drawing.Size(24, 24), System.Windows.Forms.ColorDepth.Depth32Bit);
                    iconDeviceImage.IconImage = new Bitmap(ImageUtils.ResizeImage(24, 24, resizedImage));
                    Iconex.Items.Add(iconDeviceImage);

                    // 16x16
                    iconDeviceImage = new IconDeviceImage(new System.Drawing.Size(16, 16), System.Windows.Forms.ColorDepth.Depth32Bit);
                    iconDeviceImage.IconImage = new Bitmap(ImageUtils.ResizeImage(16, 16, resizedImage));
                    Iconex.Items.Add(iconDeviceImage);
                    Iconex.Save(fileName);

                    // "Hide" the folder.ico
                    File.SetAttributes(fileName, File.GetAttributes(fileName) | FileAttributes.Hidden);

                    //imgRect.Source = ImageUtils.ConvertImageToBitmapImage(resizedImage);
                }
                catch (Exception)
                {
                    log.Add(path);
                }
            }
        }

        public void CreateDesktopIni(string path)
        {
            string fileName = path + "\\Desktop.ini";

            if (!File.Exists(fileName))
            {
                try
                {
                    StringBuilder str = new StringBuilder();
                    str.AppendLine("[.ShellClassInfo]");
                    str.AppendLine("IconResource=folder.ico,0");

                    File.WriteAllText(fileName, str.ToString());

                    // "Hide" the desktop.ini
                    File.SetAttributes(fileName, File.GetAttributes(fileName) | FileAttributes.Hidden);
                }
                catch (Exception)
                {
                    log.Add(path);
                }
            }
        }
    }

    public enum ImageOrientation
    {
        Landscape,
        Portrait
    }
}