using Discord.Commands;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
using System.Drawing.Text;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace MorphanBot
{
public partial class MorphBot
{
private const string ImageFolder = "data/images/";
public static async Task GenerateImage(CommandEventArgs e)
{
try
{
string imageName = ImageFolder + e.Args[0] + ".jpg";
if (!File.Exists(imageName))
{
StringBuilder sb = new StringBuilder();
foreach (string file in Directory.EnumerateFiles(ImageFolder))
{
sb.Append(", ").Append(file.Replace(".jpg", ""));
}
await Reply(e, "Invalid image! I currently have: " + sb.Remove(0, 2).ToString());
return;
}
Bitmap bitmap = new Bitmap(imageName);
using (Graphics graphics = Graphics.FromImage(bitmap))
{
graphics.SmoothingMode = SmoothingMode.AntiAlias;
graphics.InterpolationMode = InterpolationMode.HighQualityBicubic;
GraphicsPath path = new GraphicsPath();
StringFormat sf = new StringFormat();
Font font = new Font(new FontFamily("Impact"), 72F, FontStyle.Regular, GraphicsUnit.Pixel);
- List<string> wrapped = WrapText(graphics, e.Args[0], bitmap.Width - 200, font);
+ List<string> wrapped = WrapText(graphics, e.Args[1], bitmap.Width - 200, font);
while (font.Size > 0 && wrapped.Count > 2)
{
font = new Font(new FontFamily("Impact"), font.Size - 12F, FontStyle.Regular, GraphicsUnit.Pixel);
- wrapped = WrapText(graphics, e.Args[0], bitmap.Width - 200, font);
+ wrapped = WrapText(graphics, e.Args[1], bitmap.Width - 200, font);
}
if (font.Size <= 0)
{
await Reply(e, "Failed to write text correctly! Try shorter text!");
return;
}
int y = 60;
foreach (string s in wrapped)
{
path.AddString(s, font.FontFamily, (int)font.Style, font.Size, new Point((int)(bitmap.Width / 2F) - (int)(graphics.MeasureString(s, font).Width / 2F), y), sf);
y += (int)graphics.MeasureString(s, font).Height + 5;
}
graphics.FillPath(new SolidBrush(Color.White), path);
}
using (MemoryStream stream = new MemoryStream())
{
bitmap.Save(stream, ImageFormat.Jpeg);
stream.Seek(0, SeekOrigin.Begin);
await e.Channel.SendFile("jpg", stream);
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
Console.WriteLine(ex.StackTrace);
}
}
private static List<string> WrapText(Graphics graphics, string text, double pixels, Font font)
{
string[] originalLines = text.Split(new string[] { " " },
StringSplitOptions.None);
List<string> wrappedLines = new List<string>();
StringBuilder actualLine = new StringBuilder();
double actualWidth = 0;
foreach (string item in originalLines)
{
actualLine.Append(item + " ");
actualWidth += graphics.MeasureString(item, font).Width;
if (actualWidth > pixels)
{
wrappedLines.Add(actualLine.ToString());
actualLine.Clear();
actualWidth = 0;
}
}
if (actualLine.Length > 0)
wrappedLines.Add(actualLine.ToString());
return wrappedLines;
}
}
}