Skip to content

Instantly share code, notes, and snippets.

@HugoVG
Created July 23, 2022 14:38
Show Gist options
  • Save HugoVG/00013f714c353e054354fcff419a0d75 to your computer and use it in GitHub Desktop.
Save HugoVG/00013f714c353e054354fcff419a0d75 to your computer and use it in GitHub Desktop.
Saving a Picture as png to an server regardless of OS, png for better xamarin support, no system.drawing works on linux/windows,
using SixLabors.ImageSharp;
using SixLabors.ImageSharp.Processing;
public static class GenericHelperFunctions
{
public static bool RegChecks(string checkedto)
{
string pattern = @"^[a-zA-Z0-9_.-]*$"; // Letter and words only
Regex regex = new Regex(pattern);
DebugWrite(regex.IsMatch(checkedto));
// Compare a string against the regular expression
return regex.IsMatch(checkedto);
}
/// <summary>
/// A Picture saver using SixLabors ImageSharp
/// Works for png, jpeg, jpg, rest is untested
/// </summary>
/// <param name="file">FormFile comming from an ASP.Net API</param>
public static string SavePicture(IFormFile file)
{
string filePath = "";
string filename = "";
filename = file.FileName.Replace(".jpg", ".png").Replace(".jpeg", ".png").ToLower();
filePath = Path.Combine(FileLocations.ImageData, filename); //FileLocations in an static class with known folders
SixLabors.ImageSharp.Formats.IImageFormat h = Image.DetectFormat(file.OpenReadStream());
Image img = Image.Load(file.OpenReadStream());
img.SaveAsPng(filePath); //saves any picture format to png
return filename.ToLower();
}
/// <summary>
/// Searches a picture from the wellknown picture location
/// </summary>
public static Tuple<int, byte[]> FindImage(string name)
{
if (name == null || name == "")
return Tuple.Create<int, byte[]>(0, null); // Just being sure
name = name.Trim(); //no white spaces in the name tag like "henk "
name = name.ToLower(); // "not saving images with any UPPER characters so searching for uppercase characters is useless"
string path = FileLocations.ImageData;
if (name.IndexOf(".png") >= 0)
{
name = Path.Combine(path, name);
if (File.Exists(name))
{
byte[] picture = File.ReadAllBytes(name);
Tuple<int, byte[]> retPicture = Tuple.Create(1, picture);
return retPicture;
}
}
// If there is no extions on image it will look for one
string png = name + ".png";
png = Path.Combine(path, png);
if (File.Exists(png))
{
byte[] picture = File.ReadAllBytes(png/*Path.Combine(png)*/);
Tuple<int, byte[]> retPicture = Tuple.Create(1, picture);
DebugWrite("Found PNG");
return retPicture;
}
return Tuple.Create<int, byte[]>(0, null); //Escape Goat
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment