public void CreateImage(string imgfile)
{
wx_set mWXSet = wx_set.FetchTopOne();
if (mWXSet.IsNew)
{
throw new Exception("未配置与微信交互的相关参数");
}
FileInfo mFile = new FileInfo(imgfile);
if (mFile.Exists && mFile.LastWriteTime.AddMilliseconds(7) > DateTime.Now)
{
mFile.Open(FileMode.Open).Close();
return;
}
string accessToken = AccessTokenContainer.TryGetToken(mWXSet.appid, mWXSet.appsecret);
//int expireSenconds = 0;
int expireSenconds = 604800;
CreateQrCodeResult createQrCodeResult = QrCodeApi.Create(accessToken, expireSenconds, 10001);
if (!string.IsNullOrEmpty(createQrCodeResult.ticket))
{
using (MemoryStream stream = new MemoryStream())
{
//根据ticket获取二维码
QrCodeApi.ShowQrCode(createQrCodeResult.ticket, stream);
//将获取到的二维码图片转换为Base64String格式
//byte[] imageBytes = stream.ToArray();
//string base64Image = System.Convert.ToBase64String(imageBytes);
//由于SqlServerCompact数据库限制最长字符4000,本测试项目将二维码保存到磁盘,正式项目中可直接保存到数据库
popularizeimagecode =
WH.Business.Utilities.wjGoddess.SaveQRCodeImage(stream,
imgfile);
}
}
}
public static string SaveQRCodeImage(Stream InputStream, string filePath)
{
using (Bitmap bmp = new Bitmap(InputStream))
using (Bitmap bmp2 = new Bitmap(bmp.Width, bmp.Height, PixelFormat.Format32bppArgb))
using (Graphics draw = Graphics.FromImage(bmp2))
{
try
{
//新建第二个bitmap类型的bmp2变量,我这里是根据我的程序需要设置的。
//将第一个bmp拷贝到bmp2中
draw.DrawImage(bmp, 0, 0, bmp.Width, bmp.Height);
bmp2.Save(filePath);
LuminanceSource source = new RGBLuminanceSource(bmp2, bmp2.Width, bmp2.Height);
com.google.zxing.BinaryBitmap bitmap = new com.google.zxing.BinaryBitmap(new HybridBinarizer(source));
com.google.zxing.Result result;
result = new MultiFormatReader().decode(bitmap);
return result.Text;
}
catch (ReaderException re)
{
MyLog.Log(re.ToString());
//MessageBox.Show(re.ToString());
//return;
}
finally
{
draw.Dispose();
bmp.Dispose();//释放bmp文件资源
bmp2.Dispose();
}
}
return "";
}