* 程序的版权和版本声明部分
* Copyright (c) 2012, 烟台大学计算机学院学生
* All rights reserved.
* Copyright (c) 2012, 烟台大学计算机学院学生
* All rights reserved.
* 作 者: 刘镇
* 完成日期: 2012 年 11 月 25 日
* 版 本 号: 3.032
* 对任务及求解方法的描述部分
* 问题描述:
实现功能:1)程序运行时,用户单击“选择图片”按钮,即可打开一个“通用打开对话框”,在该对话框中,文件类型可以是*.jpg,*.gif ;2)用户选取某个图片后,该图片显示在pictureBox1中,显示方式为缩放图片适应pictureBox1。此外,该图片文件路径及完整文件名在Label1中显示出来。3)用户单击“复制图片”按钮,即可打开一个“通用保存对话框”,在该对话框中,文件扩展名类型可以是*.jpg,*.gif;用户在该对话框中输入保存后文件名即可实现复制先前所选图片。
*代码部分:
Form1.cs:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
namespace Win11_4
{
public partial class Form1 : Form
{
byte[] bytes;//用于存放图片字节数组
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
this.openFileDialog1.Filter = "*.jpg|*.jpg|*.gif|*.gif";
openFileDialog1.ShowDialog();
string openfile = this.openFileDialog1.FileName;
this.label1.Text = openfile;
if (string.IsNullOrEmpty(openfile)) return;//选择取消,则返回
this.pictureBox1.Image = Image.FromFile(openfile);
//设置图片显示模式
this.pictureBox1.SizeMode = PictureBoxSizeMode.StretchImage;
//之下是使用文件流将图片保存至字节数组
FileStream fs = new FileStream(openfile, FileMode.Open, FileAccess.Read);
bytes = new byte[fs.Length];
fs.Read(bytes, 0, bytes.Length);
fs.Dispose();
}
private void button2_Click(object sender, EventArgs e)
{
this.saveFileDialog1.Filter = "*.jpg|*.jpg|*.gif|*.gif";
saveFileDialog1.ShowDialog();
string savefile = this.saveFileDialog1.FileName;
if (string.IsNullOrEmpty(savefile)) return;//选择取消,则返回
if (bytes.Length == 0)
{
MessageBox.Show("先选图片再复制");
return;
}
//之下是使用文件流将保存在字节数组中数据复制到指定文件savefile
FileStream fs = new FileStream(savefile, FileMode.Create, FileAccess.Write);
fs.Write(bytes, 0, bytes.Length);
MessageBox.Show("图片复制成功");
fs.Dispose();
}
}
}
测试结果: