【发布时间】:2015-09-27 00:08:33
【问题描述】:
完整代码
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 WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
//Display byte array as image
private void button1_Click(object sender, EventArgs e)
{
pictureBox1.SizeMode = PictureBoxSizeMode.StretchImage;
Image img = ByteArrayToImage(File.ReadAllBytes("")); //fill with path info
pictureBox1.Image = (Image)img.Clone();
}
//Convert to image from bytes
public Image ByteArrayToImage(byte[] byteArrayIn)
{
using (MemoryStream ms = new MemoryStream(byteArrayIn))
{
ms.Position = 0;
Image returnImage = Image.FromStream(ms);
return returnImage;
}
}
//Open Image for conversion
private void loadImage_Click(object sender, EventArgs e)
{
OpenFileDialog opf = new OpenFileDialog();
DialogResult dr = new DialogResult();
dr = opf.ShowDialog();
if (dr == DialogResult.OK)
{
pictureBox1.SizeMode = PictureBoxSizeMode.StretchImage;
pictureBox1.Image = Image.FromFile(opf.FileName);
}
}
private void convertImage_Click(object sender, EventArgs e)
{
//Choose Path to Save To
SaveFileDialog saveDialog = new SaveFileDialog();
saveDialog.Title = "Choose Directory and File Name";
saveDialog.Filter = "Canga Comix *.CCMX|*.CCMX";
DialogResult dr = saveDialog.ShowDialog();
if (dr == DialogResult.OK)
{
byte[] array;
//Save Image
using (MemoryStream ms = new MemoryStream())
{
Image img = pictureBox1.Image;
img.Save(ms, System.Drawing.Imaging.ImageFormat.Png);
array = ms.ToArray();
}
using(FileStream fs = new FileStream(saveDialog.FileName, FileMode.Create))
{
fs.Write(array, 0, array.Length);
}
}
}
//clear image
private void clearImage_Click(object sender, EventArgs e)
{
pictureBox1.Image = null;
}
}
}
这些都是相当标准的。我有一个使用这些方法的测试程序。它在pictureBox 中打开一个图像,然后将其转换为byte[] 并清除pictureBox 图像。然后你可以点击 Load byte[] ,它会在运行 ByteArrayToImage 方法时正确显示图片。
然后,如果我从我的其他程序中保存一张图片并尝试在测试程序中打开它,它会给我一个邪恶的“参数无效”错误。尽管据我所知这两个文本文档完全相同。
【问题讨论】:
-
你如何保存图像?
-
请显示完整的异常以及堆栈跟踪,以及引发异常的代码。
-
正如其他人所说,“从我的其他程序中保存图片并尝试在测试程序中打开它”的代码会很有用。
-
已编辑。这就是全部。我的大程序以完全相同的方式保存图像。
标签: c# arrays image parameters bytearray