Displaying an array of images in picturebox? - c#

I'm very new to visual C# I want to display an array of images in a picture box
Here's my code:
string[] list = Directory.GetFiles(#"C:\\pictures", "*.jpg");
Image[] images = new Image[5];
for (int index = 0; index < 5; index++)
{
//HERE IS WHERE IM STUCKED WITH
picturebox[index] = Image.FromFile(list[index]);
}

Edit-1 : This answer has a scope limited to Win-Forms C#.
You need certain assemblies added in your application before using this code.
using System.IO;
using System.Windows.Forms;
Edit ended;
Original Answer
You have to draw all image to one image for displaying them in single picturebox
That is bit complex you can use mutiple pictureboxes
In following code they are created dynamically according to need:
// For confirm visibility of all images set
this.AutoScroll = true;
string[] list = Directory.GetFiles(#"C:\pictures", "*.jpg");
PictureBox[] picturebox= new PictureBox[list.Length];
int y = 0;
for (int index = 0; index < picturebox.Length; index++)
{
this.Controls.Add(picturebox[index]);
// Following three lines set the images(picture boxes) locations
if(index % 3 == 0)
y = y + 150; // 3 images per rows, first image will be at (20,150)
picturebox[index].Location=new Point(index * 120 + 20, y);
picturebox[index ].Size = new Size(100,120);
picturebox[index].Image = Image.FromFile(list[index]);
}

The answer provided throws an object reference exception. Otherwise thanks for the example!
for (int index = 0; index < picturebox.Length; index++)
{
this.Controls.Add(picturebox[index]);
// Following three lines set the images(picture boxes) locations
should be
for (int index = 0; index < picturebox.Length; index++)
{
picturebox[index] = new PictureBox();
this.Controls.Add(picturebox[index]);
// Following three lines set the images(picture boxes) locations

Use picturebox[index].Image = Image.FromFile(list[index]);

//this code help you to work with picturebox in arraye
public partial class Form_Begin : Form
{
PictureBox[] pictureBoxs = new PictureBox[50];
public Form_Begin()
{
InitializeComponent();
pictureBoxs[0] = pictureBox1;
pictureBoxs[1] = pictureBox2;
pictureBoxs[2] = pictureBox3;
pictureBoxs[3] = pictureBox4;}
List<PictureBox> pictureBoxes = new List<PictureBox>();
private void buttonX1_Click(object sender, EventArgs e)
{
for (int i = 0; i <2; i++)
{
pictureBoxs[i].Image =your_name_project.Properties.Resources.Image_1; // Load Image_1 from Resources on property of picturebox
}
for (int i = 2; i < 4; i++)
{
pictureBoxs[i].Image =your_name_project.Properties.Resources.Image_2; // Load Image_12 from Resources on property of picturebox
}

private void picbutton_Click(object sender, EventArgs e)
{
OpenFileDialog open = new OpenFileDialog();
PictureBox[] picture = new PictureBox[5];
int x = 0;
int y = 15;
for (int index = length; index < picture.Length; index++)
{
picture[index] = new PictureBox();
picture[index].Size = new Size(100, 50);
open.Title = "OPen Image";
open.Filter = "JPG Files (*.jpg)|*.jpg|JPEG Files (*.jpeg)|*.jpeg|PNG Files (*.png)|*.png|GIF Files (*.gif)|*.gif";
DialogResult result = open.ShowDialog();
if (result == DialogResult.OK)
{
picture[index].BackgroundImage = new Bitmap(open.FileName);
picture[index].SizeMode = PictureBoxSizeMode.AutoSize;
listBox1.Controls.Add(picture[index]);
if ((x % 3 == 0) && (index != 0))
{
y = y + 150; // 3 images per rows, first image will be at (20,150)
x = 0;
}
picture[index].Location = new Point(x * 210 + 20, y);
picture[index].Size = new Size(200, 150);
x++;
}
}
}

Related

Putting picturebox on picturebox

I have a problem adding picture boxes using Controls class on another picture box that already exists.
when i load the form i don't see any changes because the "coded" pictures are under the main picture (Arena)
Here is my code:
void drawSpikes()
{
PictureBox[] spikes = new PictureBox[Arena.Height / 25 * 2];
int position = 0;
byte wall = 1;
byte spike_count = 0;
for (int i = 0; i < Arena.Height / 25 * 2; i++)
{
spikes[i] = new PictureBox();
}
foreach (var Spike in spikes)
{
if (spike_count == 18) wall = 2;
Spike.Size = new Size(25, 25);
if (wall == 1)
{
Spike.Location = new Point(21, position);
Spike.BackColor = Color.Yellow;
}
if (wall == 2)
{
Spike.Location = new Point(position, 250);
Spike.BackColor = Color.Yellow;
}
if (position == 450) position = 0;
position += 25;
spike_count += 1;
Controls.Add(Spike);
}
}
How can i fix it ?
sorry for the function disconnection (i am new in stack overflow).
You can use the BringToFront() function after adding the picture box to the controls collection:
Controls.Add(Spike);
Spike.BringToFront();

c# gomoku game label array

I am trying to make a simple five in a row (gomoku) game for two players using windows forms and c#. I put a picturebox with a picture and stretched it out on the form. Now I want to put labels at all the intersections on the picture board so a user can click them and change their background color to black or white.
How can I make the labels created clickable on the form?
public partial class Form1 : Form
{
int labelCount = 0;
int iteration = 0;
public Form1()
{
InitializeComponent();
Label[] board = new Label[361];
for (int i = 0; i < 361; i++)
{
board[i] = new Label
{
Name = "label" + i,
Height = 55,
Width = 55,
MinimumSize = new Size(55, 55),
Text = "label " + i
};
}
int x = 0;
int y = 0;
foreach (var Label in board)
{
if (x >= 580)
{
x = 0;
y = y + Label.Height + 55;
}
Label.Location = new Point(x, y);
this.Controls.Add(Label);
x += Label.Width;
}
}
}
Should I make a one-dimensional [361] or two-dimensional array[{A,1}, {A,2}....{D,1}] to easily check for a winner? How can I connect it to the created labels so the array data corresponds to the objects on the board?
Well Sorry If don`t understand your question. For the Q.1 to add 361 labels you can try the code below. I hope it will help you.
public int x = 0;
public int y = 0;
private Label[] moku = new Label[361];
private void Form1_Load(object sender, EventArgs e)
{
try
{
for (int i = 0; i < 361; i++)
{
moku[i] = new Label();
moku[i].Parent = pictureBox1;//make the picturebox parent
moku[i].Location = new Point(x, y);
moku[i].Text = "O";
moku[i].Name = "moku" + i;
moku[i].BackColor = Color.Transparent;
pictureBox1.Controls.Add(moku[i]);
y += 55;
if (y >= 361) { x += 55; y = 0; x+=55; }
}
}catch(Exception er)
{
MessageBox.Show(er.ToString());
}
}
I prefer using a 2D array because it's easier if you want to check the surrounding boxes.
Form design:
Full source:
using System;
using System.Drawing;
using System.Windows.Forms;
namespace WindowsFormsApplication6
{
public enum Player
{
Empty = 0,
White,
Black
}
public partial class Form1 : Form
{
// initialize board of 5x5
private Player[,] board = new Player[5, 5];
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
DrawBoard();
}
private void DrawBoard()
{
for (var i = 0; i <= board.GetUpperBound(0); i++)
{
for (var j = 0; j <= board.GetUpperBound(1); j++)
{
// for name and text
var name = string.Format("{0}, {1}", i, j);
var label = new Label()
{
Name = name, // name of label
Size = new Size(55, 55),
BorderStyle = BorderStyle.FixedSingle,
Location = new Point(i * 55, j * 55), // location depends on iteration
Text = name
};
label.Click += ClickLabel; // subscribe the Click event handler
pictureBox1.Controls.Add(label); // add label to a container
}
}
}
// this event handler will handle all the labels click event
private void ClickLabel(object sender, EventArgs e)
{
var label = (Label)sender; // this is the label that you click
var x = Convert.ToInt32(label.Name.Split(',')[0]);
var y = Convert.ToInt32(label.Name.Split(',')[1]);
// change the color
if (radPlayerBlack.Checked)
{
// Player Black
label.ForeColor = Color.White;
label.BackColor = Color.Black;
board[x, y] = Player.Black;
}
else
{
// Player White
label.ForeColor = Color.Black;
label.BackColor = Color.White;
board[x, y] = Player.White;
}
}
}
}
You can check the value of the 2D array for black or white. Here's the value when I QuickWatch it in Visual Studio.

Split Image as Rows x Columns equal sized Image Matrix Using C#

how to split an image into Equal Size 3x3,3x4,4x4,6x6,4x6,6x8 something like that
Conceptualize by given Image: Convert simple image into that form,
In Given Answer It is General Purpose algorithm to Split an Image into proper scaled Rows x Columns Equal sized Image Matrix It Gives out put Like
1 4 7
2 5 8
3 6 9
I Used Following Code ....But It Doesn't worked perfectally
Load Button Code: Load The Image into Variable image1
Image image1;
private void btn_Open_File_BG_Click(object sender, EventArgs e)
{
OpenFileDialog openDialog = new OpenFileDialog();
if (openDialog.ShowDialog() == DialogResult.OK)
{
image1 = new Bitmap(openDialog.FileName);
}
}
Process Button Code:Split Picture & Save or Use
private void Img_BG_process_Click(object sender, EventArgs e)
{
int rows = 5;//No of Rows as per Desire
int columns = 6;//No of columns as per Desire
var imgarray = new Image[rows, columns];//Create Image Array of Size Rows X Colums
var img = image1;//Get Image from anywhere, From File Or Using Dialogbox used previously
int height = img.Height;
int width = img.Width;//Get image Height & Width of Input Image
int one_img_h = height / rows;
int one_img_w = width / columns;//You need Rows x Columns, So get 1/rows Height, 1/columns width of original Image
for (int i = 0; i < rows; i++)
{
for (int j = 0; j < columns; j++)
{
imgarray[i, j] = new Bitmap(one_img_w, one_img_h);//generating new bitmap
var graphics = Graphics.FromImage(imgarray[i, j]);
graphics.DrawImage(img, new Rectangle(0, 0, one_img_w, one_img_h), new Rectangle(i * one_img_w, j * one_img_h, one_img_w, one_img_h), GraphicsUnit.Pixel);//Generating Splitted Pieces of Image
graphics.Dispose();
}
}
//Image Is spitted You can use it by getting image from **imgarray[Rows, Columns]**
//Or You can Save it by using Following Code
var destinationFolderName = "";//Define a saving path
FolderBrowserDialog FolderBrowserDialog1 = new FolderBrowserDialog();
DialogResult result = FolderBrowserDialog1.ShowDialog();//Get folder Path Where splitted Image Saved
if (result == DialogResult.OK)
{
destinationFolderName = FolderBrowserDialog1.SelectedPath;
for (int i = 0; i < rows; i++)
{
for (int j = 0; j < columns; j++)
{
imgarray[i, j].Save(#"" + destinationFolderName + "/Image_" + i + "_" + j + ".jpg");//Save every image in Array [row][column] on local Path
}
}
}
}
Load Button Code: Load The Image into Variable image1
Image image1;
private void btn_Open_File_BG_Click(object sender, EventArgs e)
{
OpenFileDialog openDialog = new OpenFileDialog();
if (openDialog.ShowDialog() == DialogResult.OK)
{
image1 = new Bitmap(openDialog.FileName);
}
}
Process Button Code:Split Picture & Save or Use
private void Img_BG_process_Click(object sender, EventArgs e)
{
int rows = 5;//No of Rows as per Desire
int columns = 6;//No of columns as per Desire
var imgarray = new Image[rows, columns];//Create Image Array of Size Rows X Colums
var img = image1;//Get Image from anywhere, From File Or Using Dialogbox used previously
int height = img.Height;
int width = img.Width;//Get image Height & Width of Input Image
int one_img_h = height / rows;
int one_img_w = width / columns;//You need Rows x Columns, So get 1/rows Height, 1/columns width of original Image
for (int i = 0; i < rows; i++)
{
for (int j = 0; j < columns; j++)
{
imgarray[i, j] = new Bitmap(one_img_w, one_img_h);//generating new bitmap
var graphics = Graphics.FromImage(imgarray[i, j]);
graphics.DrawImage(img, new Rectangle(0, 0, one_img_w, one_img_h), new Rectangle(j * one_img_w, i * one_img_h, one_img_w, one_img_h), GraphicsUnit.Pixel);//Generating Splitted Pieces of Image
graphics.Dispose();
}
}
//Image Is spitted You can use it by getting image from **imgarray[Rows, Columns]**
//Or You can Save it by using Following Code
var destinationFolderName = "";//Define a saving path
FolderBrowserDialog FolderBrowserDialog1 = new FolderBrowserDialog();
DialogResult result = FolderBrowserDialog1.ShowDialog();//Get folder Path Where splitted Image Saved
if (result == DialogResult.OK)
{
destinationFolderName = FolderBrowserDialog1.SelectedPath;
for (int i = 0; i < rows; i++)
{
for (int j = 0; j < columns; j++)
{
imgarray[i, j].Save(#"" + destinationFolderName + "/Image_" + i + "_" + j + ".jpg");//Save every image in Array [row][column] on local Path
}
}
}
}
I think you use inadvertently "j * one_img_w, i * one_img_h" in Rectangle
SO it convert rows into columns and columns into rows

How to enable auto scroll?

I have a feeling that Im am missing something obvious but:
I have a single row of pictures in a form, in theory the pictures could go on forever. I need a scroll bar so that the user can look at all of the pictures in the row. I know I need to enable auto scroll but I have no idea how to enable it. Can someone tell me how to enable it or something that I am missing?
If it helps this is the code i am using to generate the pictures:
private void imagePalletToolStripMenuItem_Click(object sender, EventArgs e)
{
MyPalletGui.Show();
Dictionary<string,Bitmap> MyPallet = MyImageCollection.ToDictionary();
int xcor = -50;
int ycor = 0;
foreach (Bitmap curtImage in MyPallet.Values){
PictureBox myPicBox = new PictureBox();
xcor += 50;
myPicBox.Location = new Point(xcor, ycor);
myPicBox.Width = 50;
myPicBox.Height = 50;
myPicBox.Visible = true;
myPicBox.Image = new Bitmap(curtImage);
this.MyPalletGui.Controls.Add(myPicBox);
This code will do exactly what you want, it uses the Form as the ViewPort with AutoScroll:
public Form1()
{
InitializeComponent();
PopulatePictures();
}
private void PopulatePictures()
{
this.AutoScroll = true;
string[] list = Directory.GetFiles(#"C:\\Users\\Public\\Pictures\\Sample Pictures", "*.jpg");
PictureBox[] picturebox= new PictureBox[list.Length];
int y = 100;
for (int index = 0; index < picturebox.Length; index++)
{
picturebox[index] = new PictureBox();
this.Controls.Add(picturebox[index]);
picturebox[index].Location=new Point(index * 120, y);
if(x%12 == 0)
y = y + 150;
picturebox[index].Size = new Size(100,120);
picturebox[index].Image = Image.FromFile(list[index]);
}
}

Clear PictureBox - c#

I'd like to modify this PictureBox Array Project.
i want to put a reset button than will clear all the PictureBox Array it created
more likely the form will be empty again as like from the beginning.
this is some of it's code;
// Function to add PictureBox Controls
private void AddControls(int cNumber)
{
imgArray = new System.Windows.Forms.PictureBox[cNumber]; // assign number array
for (int i = 0; i < cNumber; i++)
{
imgArray[i] = new System.Windows.Forms.PictureBox(); // Initialize one variable
}
// When call this function you determine number of controls
}
private void ImagesInFolder()
{
FileInfo FInfo;
// Fill the array (imgName) with all images in any folder
imgName = Directory.GetFiles(Application.StartupPath + #"\Images");
// How many Picture files in this folder
NumOfFiles = imgName.Length;
imgExtension = new string[NumOfFiles];
for (int i = 0; i < NumOfFiles; i++)
{
FInfo = new FileInfo(imgName[i]);
imgExtension[i] = FInfo.Extension; // We need to know the Extension
//
}
}
private void ShowFolderImages()
{
int Xpos = 8;
int Ypos = 8;
Image img;
Image.GetThumbnailImageAbort myCallback =
new Image.GetThumbnailImageAbort(ThumbnailCallback);
MyProgress.Visible = true;
MyProgress.Minimum = 1;
MyProgress.Maximum = NumOfFiles;
MyProgress.Value = 1;
MyProgress.Step = 1;
string[] Ext = new string [] {".GIF", ".JPG", ".BMP", ".PNG"};
AddControls(NumOfFiles);
for (int i = 0; i < NumOfFiles; i++)
{
switch (imgExtension[i].ToUpper())
{
case ".JPG":
case ".BMP":
case ".GIF":
case ".PNG":
img = Image.FromFile(imgName[i]); // or img = new Bitmap(imgName[i]);
imgArray[i].Image = img.GetThumbnailImage(64, 64, myCallback, IntPtr.Zero);
img = null;
if (Xpos > 432) // six images in a line
{
Xpos = 8; // leave eight pixels at Left
Ypos = Ypos + 72; // height of image + 8
}
imgArray[i].Left = Xpos;
imgArray[i].Top = Ypos;
imgArray[i].Width = 64;
imgArray[i].Height = 64;
imgArray[i].Visible = true;
// Fill the (Tag) with name and full path of image
imgArray[i].Tag = imgName[i];
imgArray[i].Click += new System.EventHandler(ClickImage);
this.BackPanel.Controls.Add(imgArray[i]);
Xpos = Xpos + 72; // width of image + 8
Application.DoEvents();
MyProgress.PerformStep();
break;
}
}
MyProgress.Visible = false;
}
private bool ThumbnailCallback()
{
return false;
}
private void btnLoad_Click(object sender, System.EventArgs e)
{
ImagesInFolder(); // Load images
ShowFolderImages(); // Show images on PictureBox array
this.Text = "Click wanted image";
}
how can i do that?
sorry i don't have any code for the reset button yet.
i don't know what to do, i am new to c#.
You can just set the image to null:
private void Clear()
{
foreach (var pictureBox in imgArray)
{
pictureBox.Image = null;
pictureBox.Invalidate();
}
}
I will follow this steps to be sure everything will be fred :
private void btnReset_Click(object sender, System.EventArgs e)
{
for(int x = this.BackPanel.Controls.Count - 1; x >= 0; x--)
{
if(this.BackPanel.Controls[x].GetType() == typeof(PictureBox))
this.BackPanel.Controls.Remove(x);
}
for(int x = 0; x < imgArray.Length; x++)
{
imgArray[x].Image = null;
imgArray[x] = null;
}
}
Assuming there are no other child controls in this.Backpanel (the container control that is actually displaying your images), this will probably work:
private void ClearImages() {
this.BackPanel.Controls.Clear();
imgArray = null;
}
Good Luck!
If you are drawing on a pictureBox and you want to clear it:
Graphics g = Graphics.FromImage(this.pictureBox1.Image);
g.Clear(this.pictureBox1.BackColor);
After that you can draw again on the control.
I hope this can help to someone.

Categories

Resources