C# zxing二维码写入的实例代码
private void button1_click(object sender, eventargs e)
{
if (string.isnullorempty(this.textbox1.text.trim()))
{
messagebox.show("请输入需要转换的信息!");
return;
}
string content = textbox1.text;
hashtable hints= new hashtable();
hints.add(encodehinttype.error_correction, errorcorrectionlevel.l);//纠错级别
hints.add(encodehinttype.character_set, "utf-8");//编码格式
bytematrix bytematrix = new multiformatwriter().encode(content, barcodeformat.qr_code, 300, 300, hints);
bitmap bitmap = tobitmap(bytematrix);
picturebox1.image = bitmap;
savefiledialog sfd = new savefiledialog();
sfd.filter = "*.png|*.png";
sfd.addextension = true;
try
{
if (sfd.showdialog() == dialogresult.ok)
{
writetofile(bytematrix, system.drawing.imaging.imageformat.png, sfd.filename);
}
}
catch (exception ex)
{
messagebox.show(ex.message);
}
}
public static void writetofile(bytematrix matrix, system.drawing.imaging.imageformat format, string file)
{
system.drawing.imaging.encoderparameters eps = new system.drawing.imaging.encoderparameters();
eps.param[0] = new system.drawing.imaging.encoderparameter(system.drawing.imaging.encoder.quality, 100l);
bitmap bmap = tobitmap(matrix);
bmap.save(file, format);
}
public static bitmap tobitmap(bytematrix matrix)
{
int width = matrix.width;
int height = matrix.height;
bitmap bmap = new bitmap(width, height, system.drawing.imaging.pixelformat.format32bppargb);
for (int x = 0; x < width; x++)
{
for (int y = 0; y < height; y++)
{
bmap.setpixel(x, y, matrix.get_renamed(x, y) != -1 ? colortranslator.fromhtml("purple") : colortranslator.fromhtml("0xffffffff"));//可以自定义颜色和背景色
}
}
return bmap;
}
上一篇: C#面向对象编程基础概念汇总