How to imlement scrolling of the background in PictureBox programmatically? - c#

I have a pictureBox in my program. This pictureBox is kind a "unlimited" working area for my other controls(it's width and height growing all the time, when some of my controls located inside this pictureBox came close to pictureBox's borders). I implement scrollBars for pictureBox by myself programatically, It's just changing control's location inside the pictureBox. Now i also want to implement scrollable background. I want that backgrounds position changed as well as a controls when i scroll scrollBar. I create code for that (i simplify it for easy reading. Here is only logic for horizontal scrollBar. I call it when ScrollBar event works):
public Bitmap DrawImageUnscaled(int x, int y, int width, int height)
{
//this is the part of the image that will be cropped
Bitmap croppedPartBitmpap = new Bitmap(width, height);
Rectangle croppedPartRectangle = new Rectangle(x, y, width, height);
using (var g = Graphics.FromImage(croppedPartBitmpap))
{
//BigBitmap - original background
g.DrawImage(this.BigBitmap, 0, 0, croppedPartRectangle, GraphicsUnit.Pixel);
}
//this is the part of the image that will left
Bitmap leftPartBitmap = new Bitmap(this.PanelWidth - width, height);
Rectangle leftPartRectangle = new Rectangle(width, y,this.PanelWidth - width, height);
using (var g = Graphics.FromImage(leftPartBitmap))
{
g.DrawImage(this.BigBitmap, 0, 0, leftPartRectangle, GraphicsUnit.Pixel);
}
//this is the merged image
Bitmap mergedBitmap = new Bitmap(this.PanelWidth, this.PanelHeight);
using (var g = Graphics.FromImage(mergedBitmap))
{
g.DrawImage(leftPartBitmap, 0, 0);
g.DrawImage(croppedPartBitmpap, leftPartBitmap.Width, 0);
}
return mergedBitmap;
}
When i scroll this pictureBox area, program is cropping part of background that goes out of the boundaries and after this merged it at end with the part that been left on the screen. It works okay, but it take so much memory, it can take 2gb and more. Can you help me to avoid of using such giant memoryt? Maybe the whole logic wrong and i should try better solution for that?

Related

Drawing rectangle is overwriting existing bitmap c#

I have a grid already drawn to a picturebox and I wish to draw a rectangle in the cell the mouse is clicked in. I'm trying to do this by drawing a rectangle in the top left corner of the cell and having it fill the entire cell.
However when I click the grid disappears.
How do I make it so the grid stays?
and is there an obvious better method for doing this?
The only way to redraw the grid is by pressing the button again but I want it to stay there.
Thanks.
You need to create a Graphics
Image bm;// Or Bitmap
using (var graphics = Graphics.FromImage(bm))
{
Draw(rects, graphics);
}
private static void Draw(List<Rectangle> rectangles, Graphics graphics)
{
Pen redPen = new Pen(Color.Red, 1);
foreach (var rect in rectangles)
{
graphics.DrawRectangle(redPen, rect);
}
}
At every mouse click in the mouse_click event at first you dispose the image of the picture box and then again assign the bitmap to the picturebox image otherwise you might face out of memory exception if you click on the grid too many times
private void InitializePictureBoxImage(PictureBox pictureBox)
{
if(pictureBox.Image != null)
{
var image = pictureBox.Image; // cache it to dispose
pictureBox.Image = null; // don't dispose an used object
image.Dispose(); // and dispose of it
}
Bitmap bitmap = new Bitmap(pictureBox.Width, pictureBox.Height);
pictureBox.Image = bitmap; // assign bitmap to image
}
Then call the method in the mouse_click event which you used to draw the picture box when you press the Generate Grid button in your form. Afterwards use graphics inside the mouse_click event to colour the grid which you pressed taking the X-Y coordinate from MouseEventArgs.
Altogether I think it will be something like this
private void Mouse_ClickEvent(object sender, MouseEventArgs e)
{
InitializePictureBoxImage(pictureBox);
DrawThePictureBoxImage(pictureBox);
using (Graphics graphics = Graphics.FromImage(pictureBox.Image))
{
Color color = Color.Blue;
color = Color.FromArgb(150, color.R, color.G, color.B); // lower the opacity so the writing in the grid is visible
var brush = new SolidBrush(color);
// Calculate the starting X-Y coordinate and Width,Height of the grid to color
graphics.FillRectangle(brush, startX, startY,
width, height);
}

C# Graphics DrawImage function Re-scales bitmap extracted from an original bitmap

I have been trying to get the section of an image by giving the coordinates of the image. Here is the code that extracts image from the original image.
private byte[] ExtractImageSection(Bitmap originalMap, ImagePart imgPart)
{
Bitmap imageSection = new Bitmap(imgPart.Width, imgPart.Height);
int top = Math.Min(imgPart.Y1, imgPart.Y2);
int bottom = Math.Max(imgPart.Y1, imgPart.Y2);
int left = Math.Min(imgPart.X1, imgPart.X2);
int right = Math.Max(imgPart.X1, imgPart.X2);
Rectangle cloneRect = Rectangle.FromLTRB(left, top, right, bottom);
Graphics g = Graphics.FromImage(imageSection);
// Draw the given area (section) of the source image
// at location 0,0 on the empty bitmap (imageSection)
//g.DrawImage(originalMap, 0, 0, cloneRect, GraphicsUnit.Pixel);
g.DrawImage(originalMap, cloneRect, 0, 0, imgPart.Width, imgPart.Height, GraphicsUnit.Pixel);
/* Code Commented - Clone Bitmap method
int top = Math.Min(imgPart.Y1, imgPart.Y2);
int bottom = Math.Max(imgPart.Y1, imgPart.Y2);
int left = Math.Min(imgPart.X1, imgPart.X2);
int right = Math.Max(imgPart.X1, imgPart.X2);
Rectangle cloneRect = Rectangle.FromLTRB(left, top, right, bottom);
System.Drawing.Imaging.PixelFormat pixelFormat = originalMap.PixelFormat;
Bitmap imageSection = (Bitmap)originalMap.Clone(cloneRect, pixelFormat);*/
imageSection.Save(pageImageLocation + imgPart.ImagePartName, ImageFormat.Png);
byte[] imageSectionByte = ConvertBitmapIntoByte(imageSection);
return imageSectionByte;
}
The commented code represents the ways that I've used so far to achieve my goal. I used the following stack-overflow link to try to fix the issue but I still did not work. Here is the original image (originalMap)
Above function tries to get the highlighted section. The function gets X1, Y1, X2, Y2, Width, Heigth from front end. To get the required values I am using
imgAreaSelect
Things I have done so far to figure out the issue
I have also debugged the code to verify the coordinates, width, and
height of the extracted part. (they were correct)
Tried variants of DrawImage from Graphics class.
Tried Clone method of Bitmap to clone the original image based on the section coordinates as you can see the commented code.
Here is the image after the extract method.
Can anyone please help me figure out this workaround of the issue?

C# GDI+ ScaleTransform ok on picturebox but image saved is original

Hi I have the issue that when I use ScaleTransform(zoomFactor,zoomFactor) the image saved on disk is the original version always, while on screen in the picturebox the image is distorted in proportion to the zoomFactor.
Why this could be happening ? Shouldn't I have the final result as applied from e.Graphics on disk written image ?
My code is the following which is a version with matrix. but the instead of matrix I have used the ScaleTransform as well. Result is always the same:
g=e.Graphics;//inside picturebox_paint()
g.ScaleTransform(ratio * zoomFac, ratio * zoomFac);
e.Graphics.DrawImage((Bitmap)bmp, 0, 0);
int seed = Convert.ToInt32(Regex.Match(Guid.NewGuid().ToString(), #"\d+").Value);
String destinationFile = #"C:\tmp\photoid\" + new Random(seed).Next() + "_conv.jpg";
//Here I get always the original image back!!!!
bmp.Save(destinationFile);
I have used as well the following idiom but with same results:
//Matrix matrix = new Matrix();
//matrix.Scale(zoomFac, zoomFac);
//e.Graphics.Transform = matrix;
You need to make the PictureBox draw the things it shows on screen into a new Bitmap, which you then can save!
As it is the Image will be saved in the original form and nothing you did in the Paint event, which actually painst onto the surface of the PictureBox will be saved.
So to save everything, i.e. The Image, possibly a BackgroundImage and all you draw in the Paint event you would call DrawToBitmap somehwere.
Somewhere means somewhere else, not in the Paint event, as it will call the Paint event to create the new Bitmap, causing an endless loop..
To call it you would do something like this:
Bitmap bmpSave = new Bitmap(pictureBox1.ClientSize.Width, pictureBox1.ClientSize.Height);
pictureBox1.DrawToBitmap(bmpSave, pictureBox1.ClientRectangle);
But maybe this is not really what you want? Maybe you actually want to modify the Image? In that case do not use the Paint event at all!
Instead do something like this:
Bitmap bmpSave = new Bitmap(yourNewWidth, yourNewHeight);
using (Graphics g = Graphics.FromImage(bmpSave))
{
g.ScaleTransform(ratio * zoomFac, ratio * zoomFac);
g.DrawImage((Bitmap)pictureBox1.Image, 0, 0); //
pictureBox1.Image = bmpSave;
bmpSave.Save(...);
}
You could call this from somewhere where the scaling is being triggered from.
Note that doing the scaling repeatedly and each time from the previoulsy scaled version will degrade the quality rather fast. For this always scale from a saved version of the original!!
Btw: Using a Matrix for scaling doesn't really make a difference over ScaleTransform.
But if you want to do a direct scaling why not use the DrawImage overload which takes two Rectangles? This is the most common solution if all you want to to scale and maybe draw other stuff additionally..:
int newWidth = 100; int newHeight = 100; string yourFileName = "D:\\xyz123.jpg";
Bitmap bmpSave = new Bitmap(pictureBox1.ClientSize.Width, pictureBox1.ClientSize.Height);
Rectangle newRectangle = new Rectangle(0, 0, newWidth, newHeight);
Rectangle oldRectangle = new Rectangle(Point.Empty, pictureBox1.Image.Size);
using (Graphics g = Graphics.FromImage(bmpSave))
{
g.DrawImage((Bitmap)pictureBox1.Image, newRectangle, oldRectangle, GraphicsUnit.Pixel);
bmpSave.Save(yourFileName, ImageFormat.Jpeg);
}
And there there is the scaling Bitmap constructor:
Bitmap bmp = new Bitmap(pictureBox1.Image, newWidth, newHeight);
Which I would recommend if all you want is to scale the Image. As the other solutions it will not change the Image displayed until you assign it back into the PictureBox..:
pictureBox1.Image = bmp ;
Don't forget to dispose of the old Image..
Been a while since I messed with GDI but I think you need to copy back to the Bitmap here.
g.DrawImage(bmp, scaledwidth, scaledheight);
Try something like that before bmp.Save
Edit
Apologies for not seeing that you were copying back to the bitmap. Perhaps the overload which specifies the output rectangle is what you need. Try a DrawImage overload which has the destination Rect. https://msdn.microsoft.com/en-us/library/ms142040(v=vs.110).aspx

Changes to WriteableBitmap pixels don't update screen

I have a WriteableBitmap in a Windows Phone 8 application that is hooked up to an Image control. I'm looping through each row of the image and painting a row of pixels at a time asynchronously and then scheduling the next row for painting. However, it appears that changing the underlying pixel data does not fire a property changed so the control is not being updated. If I set the image source to a new WriteableBitmap created from the same pixels, the image updates fine but I'm doing a lot of excessive array copying.
void PaintImage(object state)
{
// get my height, width, row, etc. from the state
int[] bitmapData = new int[width];
// load the data for the row into the bitmap
Dispatcher.BeginInvoke(() =>
{
var bitmap = ImagePanel.Source as WriteableBitmap;
Array.Copy(bitmapData, 0, bitmap.Pixels, row * width, bitmapData.Length);
if (row < height - 1)
{
var newState = ... // create new state
ThreadPool.QueueUserWorkItem(PaintImage, newState);
}
});
}
If I add these lines after the Array.Copy above, the bitmap progressively is drawn to screen (although in reality it is just replacing the bitmap every time):
var newBitmap = new WriteableBitmap(width, height);
Array.Copy(bitmap.Pixels, newBitmap.Pixels, newBitmap.Pixels.Length);
ImagePanel.Source = newBitmap;
It seems like I need to manually have the WriteableBitmap fire some property changed notification so that the Image that has it. I'm guessing this problem will go away if I bind the image to a WriteableBitmap in a ViewModel?
Just add a dirty rectangle
_myBitmap.Lock();
_myBitmap.AddDirtyRect(new Int32Rect(0, 0, _myBitmap.PixelWidth, _myBitmap.PixelHeight));
_myBitmap.Unlock();
or if you are on a background thread
Application.Current.Dispatcher.InvokeAsync(() =>
{
_myBitmap.Lock();
_myBitmap.AddDirtyRect(new Int32Rect(0, 0, _myBitmap.PixelWidth, _myBitmap.PixelHeight));
_myBitmap.Unlock();
});
I think you should call Invalidate() to request for a redraw. Ref: http://msdn.microsoft.com/en-us/library/system.windows.media.imaging.writeablebitmap.invalidate(v=vs.95).aspx

c# width increased bitmap turns transparent

i tried to draw a headerCell.
original picture looks like this (increased):
I tried to stretch the images width:
Bitmap bmp = new Bitmap(3000, 1000);
Graphics graph = Graphics.FromImage(bmp);
Image headerMain = Image.FromFile(imagePfad + "header_main.jpg");
graph.DrawImage(headerMain, X, Y, 300, headerMain.Height);
Graphics g = CreateGraphics();
g.DrawImage(bmp, 0, 0);
But then it turns into transparent like this:
what am i doing wrong?
At such extreme magnifications, the work done by the interpolation filter becomes highly visible. You'll want to de-tune it to nearest-neighbor, pixel offset mode matters too:
graph.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.NearestNeighbor;
graph.PixelOffsetMode = System.Drawing.Drawing2D.PixelOffsetMode.Half;

Categories