Skip to content

Instantly share code, notes, and snippets.

@yalayabeeb
Last active December 27, 2015 12:29
Show Gist options
  • Save yalayabeeb/ee5aa36f1bc88c8df278 to your computer and use it in GitHub Desktop.
Save yalayabeeb/ee5aa36f1bc88c8df278 to your computer and use it in GitHub Desktop.
Functions to manipulate images. Planning to add more in the future. (Update: added a function to put the split images back together)
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Linq;
using System.Windows.Forms;
public static class ImageFunctions
{
public static byte[] TakeScreenshot(int monitorIndex)
{
Screen monitor = Screen.AllScreens[monitorIndex];
using (var bmp = new Bitmap(monitor.Bounds.Width, monitor.Bounds.Height))
{
using (var g = Graphics.FromImage(bmp))
g.CopyFromScreen(monitor.Bounds.X, monitor.Bounds.Y, 0, 0, monitor.Bounds.Size);
using (var ms = new MemoryStream())
{
EncoderParameters myEncoderParameters = new EncoderParameters();
myEncoderParameters.Param[0] = new EncoderParameter(Encoder.Quality, 20L);
bmp.Save(ms, GetEncoder(ImageFormat.Jpeg), myEncoderParameters);
return ms.ToArray();
}
}
}
private static ImageCodecInfo GetEncoder(ImageFormat format)
{
ImageCodecInfo[] codecs = ImageCodecInfo.GetImageDecoders();
foreach (ImageCodecInfo codec in codecs)
{
if (codec.FormatID == format.Guid)
{
return codec;
}
}
return null;
}
public static Bitmap RetrieveImage(byte[] imageData)
{
using (var ms = new MemoryStream(imageData))
{
return new Bitmap(ms);
}
}
public static IEnumerable<Bitmap> SplitImage(Bitmap src, int amount)
{
int pieces = (int)Math.Sqrt(amount);
var posY = src.Height / pieces;
var posX = src.Width / pieces;
for (var y = 0; y < pieces; y++)
for (var x = 0; x < pieces; x++)
yield return src.Clone(new Rectangle(x * posX, y * posY, posX, posY), src.PixelFormat);
}
public static Bitmap ArrangeImage(IEnumerable<Bitmap> images, int amount)
{
var pieces = (int)Math.Sqrt(amount);
var height = images.First().Height;
var width = images.First().Width;
using (var image = new Bitmap(width * pieces, height * pieces))
{
using (var g = Graphics.FromImage(image))
{
int imageCount = 0;
for (int y = 0; y < pieces; y++)
for (int x = 0; x < pieces; x++)
{
g.DrawImage(images.ElementAt(imageCount), new Rectangle(x * width, y * height, width, height));
imageCount++;
}
}
using (var ms = new MemoryStream())
{
image.Save(ms, ImageFormat.Png);
return new Bitmap(ms);
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment