using System;
using System.Diagnostics;
using System.Drawing.Printing;
using System.IO;
using UnityEngine;
namespace LCPrinter
{
public static class Prints
{
//打印图片(图片的字节流,打印张数,打印的名字)
public static void PrintTexture(byte[] texture2DBytes, int numCopies, string printerName)
{
//字节流是否为空
if (texture2DBytes == null)
{
//输出提示
UnityEngine.Debug.LogWarning("LCPrinter: Texture is empty.");
return;
}
//打印设置新建对象
PrinterSettings printerSettings = new PrinterSettings();
//打印名字为空或者等于空
if (printerName == null || printerName.Equals(""))
{
printerName = printerSettings.PrinterName;
UnityEngine.Debug.Log("LCPrinter: Printing to default printer (" + printerName + ").");
}
//储存时间段信息
string str = string.Concat(new string[]
{
DateTime.Now.Year.ToString(),
"-",
DateTime.Now.Month.ToString(),
"-",
DateTime.Now.Day.ToString(),
"-",
DateTime.Now.Hour.ToString(),
"-",
DateTime.Now.Minute.ToString(),
"-",
DateTime.Now.Second.ToString(),
"-",
DateTime.Now.Millisecond.ToString()
});
//文本
string text = (Application.persistentDataPath + "\\LCPrinterFiletmp_" + str + ".png").Replace("/", "\\");
UnityEngine.Debug.Log("LCPrinter: Temporary Path - " + text);
//字节流写入
File.WriteAllBytes(text, texture2DBytes);
Prints.PrintCMD(text, numCopies, printerName);
}
//通过纹理路径(路径,打印张数,输出的名字)
public static void PrintTextureByPath(string path, int numCopies, string printerName)
{
//打印机设置
PrinterSettings printerSettings = new PrinterSettings();
//判断是否为空
if (printerName == null || printerName.Equals(""))
{
//设置打印的名字
printerName = printerSettings.PrinterName;
UnityEngine.Debug.Log("LCPrinter: Printing to default printer (" + printerName + ").");
}
Prints.PrintCMD(path, numCopies, printerName);
}
//CMD
private static void PrintCMD(string path, int numCopies, string printerName)
{
//对进程的控制
Process process = new Process();
try
{
for (int i = 0; i < numCopies; i++)
{
process.StartInfo.FileName = "rundll32";
process.StartInfo.Arguments = string.Concat(new string[]
{
"C:\\WINDOWS\\system32\\shimgvw.dll,ImageView_PrintTo \"",
path,
"\" \"",
printerName,
"\""
});
process.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
process.StartInfo.UseShellExecute = true;
process.Start();
}
}
catch (Exception arg)
{
UnityEngine.Debug.LogWarning("LCPrinter: " + arg);
}
finally
{
process.Close();
UnityEngine.Debug.Log("LCPrinter: Texture printing.");
}
}
}
}
使用时需要Using 命名空间,然后通过Prints.PrintTexture()方法来打印。
举个栗子:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using LCPrinter;
public class demo : MonoBehaviour {
public Texture2D screenShot;
void test()
{
Prints.PrintTexture(screenShot.EncodeToPNG(), 1, "");
}
}
这里并没有给打印机名字是使用默认的打印机,需要自己设置。
需要注意的是texture2D的分辨率是否符合打印机默认的尺寸。