简体   繁体   中英

How to load image from disk according to selected index in listBox?

Once i finish drawing a rectangle i'm saving the image to the hard disk as bitmap, adding to a listBox the image number and the rectangle location and size in the end i'm creating a text file with the information.

private void pictureBox2_MouseUp(object sender, MouseEventArgs e)
        {
            if (e.Button != MouseButtons.Left) return;

            if (DrawingRects.Count > 0)
            {
                // The last drawn shape
                var dr = DrawingRects.Last();
                if (dr.Rect.Width > 0 && dr.Rect.Height > 0)
                {
                    rectImage = cropAtRect((Bitmap)pictureBox2.Image, dr.Rect);
                    if (saveRectangles)
                    {
                        rectangleName = @"d:\Rectangles\rectangle" + saveRectanglesCounter + ".bmp";
                        rectImage.Save(rectangleName);
                        saveRectanglesCounter++;
                    }
                    pixelsCounter = rect.Width * rect.Height;
                    pictureBox1.Invalidate();

                    // ListBox used to present the shape coordinates
                    listBox1.Items.Add($"{dr.Location}, {dr.Size}");

                    StreamWriter w = new StreamWriter(@"d:\Rectangles\rectangles.txt", true);
                    w.WriteLine(rectangleName.Substring(23) + " ===> " + $"{dr.Location}, {dr.Size}");
                    w.Close();
                }
            }
        }

The result is:

On the left is the listBox with the items on the right the content of the text file and the images on the hard disk.

图片

what i want to do is while drawing rectangles and the application is running to be able to move between the items in the listBox and display the saved images in the pictureBox1 and also when running the application over again to read the text file content and add back the items in the format they are in the listBox back to the listBox and again to be able to move between the items and display the images.

not sure how to know what image belond to what item in the listBox and then how to load it in the selected index event.

private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
        {
            foreach (int x in listBox1.SelectedIndices)
            {
                
            }
        }

full code

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using static System.Net.Mime.MediaTypeNames;
using static System.Windows.Forms.VisualStyles.VisualStyleElement.ProgressBar;

namespace Image_Crop
{
    public partial class Form1 : Form
    {
        System.Drawing.Image img = null;
        Rectangle rect;
        int pixelsCounter = 0;
        Color SelectedColor = Color.LightGreen;
        List<DrawingRectangle> DrawingRects = new List<DrawingRectangle>();
        Bitmap rectImage;
        int saveRectanglesCounter = 1;
        bool drawBorder = true;
        bool clearRectangles = true;
        bool saveRectangles = true;
        string rectangleName;

        public Form1()
        {
            InitializeComponent();

            pictureBox2.Image = System.Drawing.Image.FromFile(@"d:\Comparison\ConvertedBmp.bmp");
img = System.Drawing.Image.FromFile(@"d:\Comparison\radar_without_clouds.jpg");

            checkBoxDrawBorder.Checked = true;
            checkBoxClearRectangles.Checked = true;
            checkBoxSaveRectangles.Checked = true;
            
        }

        public class DrawingRectangle
        {
            public Rectangle Rect => new Rectangle(Location, Size);
            public Size Size { get; set; }
            public Point Location { get; set; }
            public Control Owner { get; set; }
            public Point StartPosition { get; set; }
            public Color DrawingcColor { get; set; } = Color.LightGreen;
            public float PenSize { get; set; } = 3f;
        }

        private void Form1_Load(object sender, EventArgs e)
        {

        }

        private void button1_Click(object sender, EventArgs e)
        {
            if (img == null)
            {
                // Create image.
                img = System.Drawing.Image.FromFile(@"d:\Comparison\ConvertedBmp.bmp");
            }
        }

        private void Form1_Paint(object sender, PaintEventArgs e)
        {

        }

        private void pictureBox2_MouseDown(object sender, MouseEventArgs e)
        {
            if (e.Button != MouseButtons.Left) return;
            DrawingRects.Add(new DrawingRectangle()
            {
                Location = e.Location,
                Size = Size.Empty,
                StartPosition = e.Location,
                Owner = (Control)sender,
                DrawingcColor = SelectedColor // <= Shape's Border Color
            });
        }

        private void pictureBox2_MouseMove(object sender, MouseEventArgs e)
        {
            if (e.Button != MouseButtons.Left) return;

            var dr = DrawingRects[DrawingRects.Count - 1];
            if (e.Y < dr.StartPosition.Y) { dr.Location = new Point(dr.Rect.Location.X, e.Y); }
            if (e.X < dr.StartPosition.X) { dr.Location = new Point(e.X, dr.Rect.Location.Y); }

            dr.Size = new Size(Math.Abs(dr.StartPosition.X - e.X), Math.Abs(dr.StartPosition.Y - e.Y));
            pictureBox2.Invalidate();
        }

        private void pictureBox2_MouseUp(object sender, MouseEventArgs e)
        {
            if (e.Button != MouseButtons.Left) return;

            if (DrawingRects.Count > 0)
            {
                // The last drawn shape
                var dr = DrawingRects.Last();
                if (dr.Rect.Width > 0 && dr.Rect.Height > 0)
                {
                    rectImage = cropAtRect((Bitmap)pictureBox2.Image, dr.Rect);
                    if (saveRectangles)
                    {
                        rectangleName = @"d:\Rectangles\rectangle" + saveRectanglesCounter + ".bmp";
                        rectImage.Save(rectangleName);
                        saveRectanglesCounter++;
                    }
                    pixelsCounter = rect.Width * rect.Height;
                    pictureBox1.Invalidate();

                    // ListBox used to present the shape coordinates
                    listBox1.Items.Add($"{dr.Location}, {dr.Size}");

                    StreamWriter w = new StreamWriter(@"d:\Rectangles\rectangles.txt", true);
                    w.WriteLine(rectangleName.Substring(23) + " ===> " + $"{dr.Location}, {dr.Size}");
                    w.Close();
                }
            }
        }

        private void pictureBox2_Paint(object sender, PaintEventArgs e)
        {
            DrawShapes(e.Graphics);
        }

        private void pictureBox1_Paint(object sender, PaintEventArgs e)
        {
            if (drawBorder)
            {
                ControlPaint.DrawBorder(e.Graphics, pictureBox1.ClientRectangle, Color.Red, ButtonBorderStyle.Solid);
            }

            if (rectImage != null && DrawingRects.Count > 0)
            {
                var dr = DrawingRects.Last();
                e.Graphics.DrawImage(rectImage, dr.Rect);

                if (clearRectangles)
                {
                    DrawingRects.Clear();
                    pictureBox2.Invalidate();
                }
            }
        }

        private void DrawShapes(Graphics g)
        {
            if (DrawingRects.Count == 0) return;
            g.SmoothingMode = SmoothingMode.AntiAlias;
            foreach (var dr in DrawingRects)
            {
                using (Pen pen = new Pen(dr.DrawingcColor, dr.PenSize))
                {
                    g.DrawRectangle(pen, dr.Rect);
                };
            }
        }

        public Bitmap cropAtRect(Bitmap b, Rectangle r)
        {
            Bitmap nb = new Bitmap(r.Width, r.Height);
            using (Graphics g = Graphics.FromImage(nb))
            {
                g.DrawImage(b, -r.X, -r.Y);
                return nb;
            }
        }

        private void checkBoxDrawBorder_CheckedChanged(object sender, EventArgs e)
        {
            if(checkBoxDrawBorder.Checked)
            {
                drawBorder = true;
            }
            else
            {
                drawBorder = false;
            }

            pictureBox1.Invalidate();
        }

        private void checkBoxClearRectangles_CheckedChanged(object sender, EventArgs e)
        {
            if(checkBoxClearRectangles.Checked)
            {
                clearRectangles = true;
            }
            else
            {
                clearRectangles = false;
            }

            pictureBox2.Invalidate();
        }

        private void checkBoxSaveRectangles_CheckedChanged(object sender, EventArgs e)
        {

        }

        private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
        {
            foreach (int x in listBox1.SelectedIndices)
            {
                
            }
        }
    }
}

Sorry, I hid some part of the code for a nice look, I hope you will understand. You can use the Dictionary to match the name and path:

Dictionary<string, string> FileList = new Dictionary<string, string>();

private void pictureBox2_MouseUp(object sender, MouseEventArgs e)
{
    // ...
    if (saveRectangles)
    {
        // ...
        FileList.Add($"{dr.Location}, {dr.Size}", rectangleName);
    }
    // ...
}

private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
{
    yourPictureBox.Image = Image.FromFile(FileList
        .Where(x => x.Key == ((ListBox)sender).SelectedItem?.ToString())
        .Select(x => x.Value).First()
    );
}

If in the future you need to save these key pairs, it seems to me that it will be convenient for you to use saving them to a configuration file in JSON format. To do this, you need to connect the Newtonsoft.Json package. For this package, the documentation is here .

Here is a small example of saving and loading paths:

// Path of demo config file
string Path = $@"{Environment.CurrentDirectory}\data.json";
Dictionary<string, string> PathList = new Dictionary<string, string>();

// Checking config file data.json in current directory
if(!File.Exists(Path))
{
    // Loading demos data if config file not found
    PathList.Add("path1", "value1");
    PathList.Add("path2", "value2");
}            
else
{
    // If demo config file found - upload him
    // by specifying the type Dictionary<string, string>
    using (StreamReader sr = new StreamReader(Path))                
        PathList = JsonConvert.DeserializeObject<Dictionary<string, string>>(sr.ReadToEnd());                
}

// Showing the config keys
ListBoxKeys.Items.AddRange(PathList.Select(x => x.Key).ToArray());
// Showing the config value by selected index
ListBoxKeys.SelectedIndexChanged += (s, e) =>
{
    LabelValue.Text = PathList
        .Where(x => x.Key == ((ListBox)s).SelectedItem?.ToString())
        .Select(x => x.Value).First();
};

// Saving data list to demo config file
ButtonSave.Click += (s, e) =>
{
    using (StreamWriter sw = new StreamWriter(Path))
        sw.WriteLine(JsonConvert.SerializeObject(PathList, Formatting.Indented));
};

在此处输入图像描述

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM