读取图像到图片框
本文关键字:图像 读取 | 更新日期: 2023-09-27 18:08:34
我正在尝试读取图像到文件。我在下面写代码;
for ( int i = 0; i < filePaths.Length; i++ )
{
pictureBox1.Image = imList.Images[i];
pictureBox1.SizeMode = PictureBoxSizeMode.Normal;
Application.DoEvents();
Thread.Sleep(1000);
}
但是图像分辨率很差。当我只写下面的代码;
pictureBox1.Image = imList.Images[i];
pictureBox1.SizeMode = PictureBoxSizeMode.Normal;
不是问题。分辨率很好。我尝试了不同的大小模式,但没有改变。我有什么问题?提前谢谢。
从注释中添加代码。
ImageList imList = new ImageList();
此处为In循环
filePath = @"C:'Users'OSMAN'documents'visual studio 2013'Projects'WindowsFormsApplication2'WindowsFormsApplication2'Yaprak'" + j ; string[] filePaths = Directory.GetFiles(filePath,"*.jpg");
在调用do事件后,您正在休眠UI线程,这可能还没有完成以全分辨率渲染图片。当它醒来后,是时候再次改变画面了!
更好的方法是不从UI线程加载图片;相反,运行一个单独的线程,并根据需要在那里休眠。下面的示例假设您从按钮单击事件开始流程:
private void button1_Click(object sender, EventArgs e)
{
Task.Factory.StartNew(() => LoadPics());
// if TPL not available
// use Action delegate
// Not showing endinvoke here
// var action = new Action(LoadPics);
// action.BeginInvoke(null, null);
}
private void SetImage(Image img)
{
pictureBox1.Image = img;
pictureBox1.SizeMode = PictureBoxSizeMode.Normal;
}
private void LoadPics()
{
for ( int i = 0; i < filePaths.Length; i++ )
{
// Invoke UI thread for changing picture
pictureBox1.Invoke(new Action(() => SetImage(imList.Images[i])));
Thread.Sleep(1000);
}
}
看起来你正在尝试做某种幻灯片放映。我认为你的问题是如何刷新形象。你可能想尝试将图像添加到不同的图片holder中,堆叠它们,然后发送到后台。这将创建幻灯片放映。如果这不是你的意图,请澄清你的问题或需求。
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
private void Form1_Load(object sender, EventArgs e)
{
var left = pictureBox1.Left;
var top = pictureBox1.Top;
var width = pictureBox1.Width;
var height = pictureBox1.Height;
var form = this;
var currPictureBox = pictureBox1;
new Thread(new ThreadStart(() =>
{
for (var x = 1; x < 3; x++)
{
ExecuteSecure(() =>
{
var pictureBox = new PictureBox
{
Width = width,
Height = height,
Top = top,
Left = left,
ImageLocation = @"C:'filelocation" + x + ".jpg"
};
form.Controls.Remove(currPictureBox);
form.Controls.Add(pictureBox);
currPictureBox = pictureBox;
form.Refresh();
});
Thread.Sleep(1000);
}
})).Start();
}
private void ExecuteSecure(Action a)
{
if (InvokeRequired) BeginInvoke(a);
else a();
}