Reputation: 35
I have a question that how can we get pixels of only last row of an image and display that row in a picturebox of C# application.
Upvotes: 1
Views: 203
Reputation: 205779
The easiest (but also fastest) way I see is to use the following Bitmap Constructor (Int32, Int32, Int32, PixelFormat, IntPtr) overload in combination with Bitmap.LockBits / Bitmap.UnlockBits like this
static Bitmap GetLastRow(Bitmap source)
{
var data = source.LockBits(new Rectangle(0, source.Height - 1, source.Width, 1), ImageLockMode.ReadOnly, source.PixelFormat);
try { return new Bitmap(data.Width, data.Height, data.Stride, data.PixelFormat, data.Scan0); }
finally { source.UnlockBits(data); }
}
In general you can use this code to crop any rectangular part of a bitmap by just changing the new Rectangle(...)
part.
Update: It turns out that there is even a predefined method - Bitmap.Clone(Rectangle, PixelFormat), so the code could be simply
Bitmap source = ...;
var lastRow = source.Clone(new Rectangle(0, source.Height - 1, source.Width, 1), source.PixelFormat);
Upvotes: 2
Reputation: 3497
public Bitmap LastRow(Bitmap source)
{
int y = source.Height - 1;
Bitmap newSource = new Bitmap(source.Width, 1);
for (int x = 0; x < source.Width; x++)
{
NewSource.SetPixel(x, y, Source.GetPixel(x, y));
}
return newSource;
}
Sample usage:
pictureBox1.Image = LastRow(yourImage);
Upvotes: 1
Reputation: 168
Probably not the fastest way, but should work:
Bitmap image1 = new Bitmap(@"picture.bmp");
Bitmap image2 = new Bitmap(image1.Width, 1, image1.PixelFormat);
for (int i = 0; i < image1.Width; i++)
{
image2.SetPixel(i, 0, image1.GetPixel(i, image1.Height - 1));
}
pictureBox1.Image = image2;
Upvotes: 0