项目 4 任务 2 网络摄像机:PictureBox、Image / Bitmap、照片列表
CI/CD / test (push) Canceled after 0s
CI/CD / deploy (push) Canceled after 0s

- 摄像头:自绘东围墙场景(Camera/scene.svg),按云台位置切成 640×480 帧(build-frames.ts);
  Pan 每次转一格,红外对射被遮挡时画面出现翻墙的人;类名、委托、事件参数与教材 dll 一致,
  ImageRead 每 250 ms 在后台线程触发
- Image / Bitmap 保存真实图片数据:Save、FromFile、FromStream,文件夹不存在时报 GDI+ 一般性错误;
  图片每张只发给浏览器一次(按内容哈希缓存)
- 程序所在目录(AppDomain.CurrentDomain.BaseDirectory,编译检查单独放行)和当前目录指向可写的 bin/Debug,
  沙箱里在沙箱的临时目录
- PictureBox(SizeMode、BorderStyle);设计器工具箱加"图片框";运行区显示程序保存的图片,点开看大图;
  实训台摄像头图标显示开启状态
- 评分规则加图片框显示图片、摄像头开关与转向、保存图片三种检查;示例 p4-t2-网络摄像机
- 测试:摄像头端到端、图片读写与程序目录、AppDomain 编译检查、评分出错情况

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
xuyueandClaude Opus 5.5 committed 2026-10-22 20:58:09 +08:00
1 parent 4ed9450c02
commit 6b088240da
76 files changed
+1290 -14

No files matched your search

@@ -0,0 +1,48 @@
// 生成网络摄像机的画面帧:把 scene.svg 渲染成全景图(有人翻墙 / 没有人两种),按云台位置切成 640×480 的 JPEG。
// 帧文件提交在仓库里,改了 scene.svg 后重新运行:bun runtime/Sim.Devices/Camera/build-frames.ts
// 需要 rsvg-convert(librsvg)和 magick(ImageMagick)。
import { mkdir, rm } from 'node:fs/promises'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
/** 与 IPCameraHelper.cs 中的常量一致 */
const VIEW = { width: 640, height: 480 }
const STEPS = { x: 7, y: 3 }
const STRIDE = { x: 200, y: 160 }
const dir = import.meta.dir
const framesDir = join(dir, 'frames')
const work = join(tmpdir(), `camera-frames-${process.pid}`)
async function run(cmd: string[]) {
const proc = Bun.spawn(cmd, { stderr: 'inherit' })
if ((await proc.exited) !== 0) throw new Error(`${cmd[0]} 失败`)
}
const scene = await Bun.file(join(dir, 'scene.svg')).text()
const intruder = scene
.replace('id="intruder" display="none"', 'id="intruder"')
.replace('<path id="beam" ', '<path id="beam" display="none" ')
.replace('id="beam-broken" display="none"', 'id="beam-broken"')
if (intruder === scene) throw new Error('scene.svg 里找不到 #intruder')
await rm(framesDir, { recursive: true, force: true })
await mkdir(framesDir, { recursive: true })
await mkdir(work, { recursive: true })
try {
for (const [flag, svg] of [[0, scene], [1, intruder]] as const) {
const svgPath = join(work, `scene-${flag}.svg`)
const pngPath = join(work, `scene-${flag}.png`)
await Bun.write(svgPath, svg)
await run(['rsvg-convert', svgPath, '-o', pngPath])
for (let x = 0; x < STEPS.x; x++) {
for (let y = 0; y < STEPS.y; y++) {
const crop = `${VIEW.width}x${VIEW.height}+${x * STRIDE.x}+${y * STRIDE.y}`
await run(['magick', pngPath, '-crop', crop, '+repage', '-strip', '-quality', '80', join(framesDir, `${x}-${y}-${flag}.jpg`)])
}
}
}
} finally {
await rm(work, { recursive: true, force: true })
}
console.log(`已生成 ${STEPS.x * STEPS.y * 2} 帧:${framesDir}`)
Binary file not shown.

After

Width:  |  Height:  |  Size: 14 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 14 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 19 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 19 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 19 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 19 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 17 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 17 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 22 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 22 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 20 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 20 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 18 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 20 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 22 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 25 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 20 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 22 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 20 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 21 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 24 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 26 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 21 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 22 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 19 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 20 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 23 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 25 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 21 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 23 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 18 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 16 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 23 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 21 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 22 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 20 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 15 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 15 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 20 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 19 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 20 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 19 KiB

+151
View File
@@ -0,0 +1,151 @@
<svg xmlns="http://www.w3.org/2000/svg" width="1840" height="800" viewBox="0 0 1840 800">
<!-- 网络摄像机看到的场景:从校园里望向东围墙。摄像机视野 640×480,左右 7 档、上下 3 档(见 build-frames.ts)。
#intruder 是翻墙的人,实训台红外对射被遮挡时显示,同时对射光束断开(#beam)。 -->
<defs>
<linearGradient id="sky" x1="0" y1="0" x2="0" y2="1">
<stop offset="0" stop-color="#7cb9e8"/>
<stop offset="1" stop-color="#d4ecfa"/>
</linearGradient>
<linearGradient id="lawn" x1="0" y1="0" x2="0" y2="1">
<stop offset="0" stop-color="#8cc66d"/>
<stop offset="1" stop-color="#6aa84f"/>
</linearGradient>
<pattern id="bricks" width="60" height="30" patternUnits="userSpaceOnUse">
<rect width="60" height="30" fill="#c96f4a"/>
<path d="M0 15h60M0 30h60M30 0v15M0 15v15M60 15v15" stroke="#a65638" stroke-width="2"/>
</pattern>
<g id="tree">
<rect x="-7" y="-10" width="14" height="70" fill="#7a5230"/>
<circle cx="0" cy="-50" r="48" fill="#4f9a45"/>
<circle cx="-30" cy="-25" r="34" fill="#5aa84f"/>
<circle cx="30" cy="-25" r="34" fill="#468c3e"/>
</g>
<g id="pine">
<rect x="-6" y="-10" width="12" height="40" fill="#6b4a2b"/>
<path d="M0 -130 L45 -10 H-45 Z" fill="#3f7f45"/>
<path d="M0 -150 L35 -60 H-35 Z" fill="#4a8f4f"/>
</g>
<g id="cloud" fill="#ffffff" opacity="0.92">
<ellipse cx="0" cy="0" rx="70" ry="26"/>
<ellipse cx="-40" cy="8" rx="45" ry="20"/>
<ellipse cx="45" cy="6" rx="50" ry="22"/>
<ellipse cx="5" cy="-18" rx="40" ry="24"/>
</g>
</defs>
<!-- 天空和云 -->
<rect width="1840" height="460" fill="url(#sky)"/>
<circle cx="1620" cy="110" r="46" fill="#ffe27a"/>
<use href="#cloud" x="210" y="110"/>
<use href="#cloud" x="760" y="70" transform="scale(1)"/>
<use href="#cloud" x="1250" y="150"/>
<use href="#cloud" x="1700" y="250"/>
<use href="#cloud" x="420" y="260"/>
<!-- 墙外远处的楼房 -->
<g fill="#b9c7d6">
<rect x="40" y="250" width="150" height="220"/>
<rect x="230" y="300" width="110" height="170"/>
<rect x="1450" y="230" width="170" height="240"/>
<rect x="1660" y="290" width="130" height="180"/>
</g>
<g fill="#e6eef6">
<rect x="60" y="270" width="24" height="18"/><rect x="104" y="270" width="24" height="18"/><rect x="148" y="270" width="24" height="18"/>
<rect x="60" y="310" width="24" height="18"/><rect x="104" y="310" width="24" height="18"/><rect x="148" y="310" width="24" height="18"/>
<rect x="60" y="350" width="24" height="18"/><rect x="104" y="350" width="24" height="18"/><rect x="148" y="350" width="24" height="18"/>
<rect x="1470" y="250" width="26" height="20"/><rect x="1520" y="250" width="26" height="20"/><rect x="1570" y="250" width="26" height="20"/>
<rect x="1470" y="295" width="26" height="20"/><rect x="1520" y="295" width="26" height="20"/><rect x="1570" y="295" width="26" height="20"/>
<rect x="1470" y="340" width="26" height="20"/><rect x="1520" y="340" width="26" height="20"/><rect x="1570" y="340" width="26" height="20"/>
</g>
<!-- 墙外的教学楼(对面学校) -->
<rect x="560" y="200" width="620" height="270" fill="#f2e3c9"/>
<rect x="540" y="185" width="660" height="22" fill="#c98b5a"/>
<rect x="820" y="140" width="100" height="50" fill="#f2e3c9"/>
<rect x="810" y="130" width="120" height="14" fill="#c98b5a"/>
<circle cx="870" cy="166" r="16" fill="#ffffff" stroke="#8a6a4a" stroke-width="3"/>
<path d="M870 166 V156 M870 166 H878" stroke="#8a6a4a" stroke-width="3"/>
<g fill="#7fa6c8">
<rect x="590" y="225" width="50" height="40"/><rect x="670" y="225" width="50" height="40"/><rect x="750" y="225" width="50" height="40"/>
<rect x="940" y="225" width="50" height="40"/><rect x="1020" y="225" width="50" height="40"/><rect x="1100" y="225" width="50" height="40"/>
<rect x="590" y="295" width="50" height="40"/><rect x="670" y="295" width="50" height="40"/><rect x="750" y="295" width="50" height="40"/>
<rect x="940" y="295" width="50" height="40"/><rect x="1020" y="295" width="50" height="40"/><rect x="1100" y="295" width="50" height="40"/>
<rect x="590" y="365" width="50" height="40"/><rect x="670" y="365" width="50" height="40"/><rect x="750" y="365" width="50" height="40"/>
<rect x="940" y="365" width="50" height="40"/><rect x="1020" y="365" width="50" height="40"/><rect x="1100" y="365" width="50" height="40"/>
</g>
<rect x="835" y="380" width="70" height="90" fill="#8a6a4a"/>
<!-- 墙外的树 -->
<use href="#pine" x="420" y="470"/>
<use href="#pine" x="1300" y="470"/>
<use href="#pine" x="1380" y="475"/>
<!-- 东围墙 -->
<rect x="0" y="440" width="1840" height="140" fill="url(#bricks)"/>
<rect x="0" y="428" width="1840" height="16" fill="#e8d8c4"/>
<g fill="#b5603f">
<rect x="0" y="420" width="40" height="160"/>
<rect x="460" y="420" width="40" height="160"/>
<rect x="920" y="420" width="40" height="160"/>
<rect x="1380" y="420" width="40" height="160"/>
<rect x="1800" y="420" width="40" height="160"/>
</g>
<g fill="#e8d8c4">
<rect x="-6" y="412" width="52" height="12"/><rect x="454" y="412" width="52" height="12"/>
<rect x="914" y="412" width="52" height="12"/><rect x="1374" y="412" width="52" height="12"/>
<rect x="1794" y="412" width="52" height="12"/>
</g>
<!-- 墙头的红外对射:两个探头和红色光束 -->
<g>
<rect x="474" y="384" width="16" height="28" rx="3" fill="#3a3f47"/>
<rect x="478" y="390" width="8" height="6" fill="#e04040"/>
<rect x="1384" y="384" width="16" height="28" rx="3" fill="#3a3f47"/>
<rect x="1388" y="390" width="8" height="6" fill="#e04040"/>
<path id="beam" d="M490 393 H1384" stroke="#ff3b3b" stroke-width="2" stroke-dasharray="10 6" opacity="0.8"/>
<g id="beam-broken" display="none" stroke="#ff3b3b" stroke-width="2" stroke-dasharray="10 6" opacity="0.8">
<path d="M490 393 H880"/>
</g>
</g>
<!-- 翻墙的人 -->
<g id="intruder" display="none">
<!-- 腿:一条跨在墙头,一条垂在墙里侧 -->
<path d="M905 430 L870 470 L880 520" stroke="#2f3b55" stroke-width="18" fill="none" stroke-linecap="round" stroke-linejoin="round"/>
<path d="M915 430 L955 455 L985 440" stroke="#2f3b55" stroke-width="18" fill="none" stroke-linecap="round" stroke-linejoin="round"/>
<ellipse cx="882" cy="526" rx="16" ry="8" fill="#222"/>
<!-- 身体 -->
<path d="M890 360 Q910 350 930 362 L925 435 H895 Z" fill="#2c2c2c"/>
<!-- 手臂撑在墙头 -->
<path d="M895 372 L860 410 L870 428" stroke="#2c2c2c" stroke-width="14" fill="none" stroke-linecap="round" stroke-linejoin="round"/>
<path d="M928 372 L955 405 L945 428" stroke="#2c2c2c" stroke-width="14" fill="none" stroke-linecap="round" stroke-linejoin="round"/>
<!-- 头和帽子 -->
<circle cx="910" cy="332" r="22" fill="#e9b88f"/>
<path d="M887 330 Q910 296 934 330 Z" fill="#1d1d1d"/>
<rect x="895" y="328" width="30" height="7" fill="#1d1d1d"/>
<!-- 背包 -->
<rect x="922" y="372" width="22" height="34" rx="5" fill="#8b3a3a"/>
</g>
<!-- 墙里侧:草地、小路、路灯、树、灌木 -->
<rect x="0" y="580" width="1840" height="220" fill="url(#lawn)"/>
<path d="M0 640 Q600 610 1000 650 T1840 630 V700 Q1300 720 900 700 T0 720 Z" fill="#d9c9a8"/>
<g fill="#3f8a3a">
<ellipse cx="120" cy="590" rx="90" ry="30"/>
<ellipse cx="700" cy="592" rx="110" ry="28"/>
<ellipse cx="1160" cy="590" rx="100" ry="30"/>
<ellipse cx="1640" cy="592" rx="120" ry="30"/>
</g>
<use href="#tree" x="300" y="640"/>
<use href="#tree" x="1560" y="650"/>
<g>
<rect x="1236" y="470" width="10" height="200" fill="#505a66"/>
<path d="M1241 476 Q1241 450 1275 450 H1290" stroke="#505a66" stroke-width="8" fill="none"/>
<rect x="1280" y="446" width="34" height="12" rx="4" fill="#3d4652"/>
<ellipse cx="1297" cy="460" rx="14" ry="4" fill="#fff6c4"/>
</g>
<g fill="#6aa84f">
<circle cx="40" cy="770" r="6"/><circle cx="520" cy="760" r="5"/><circle cx="980" cy="775" r="6"/>
<circle cx="1420" cy="765" r="5"/><circle cx="1780" cy="772" r="6"/>
</g>
</svg>

After

Width:  |  Height:  |  Size: 8.1 KiB

@@ -17,6 +17,7 @@ public class DeviceCtrlHelper
public static ADAM4017Helper adam4017Helper = new();
public static ADAM4150Helper adam4150Helper = new();
public static ZigBeeHelper zigBeeHelper = new();
public static IPCameraHelper ipCameraHelper = new();
}
public class SerialPortHelper
@@ -0,0 +1,127 @@
using System;
using System.Drawing;
using System.IO;
using System.Threading;
using Sim.Host;
namespace DeviceCtrlLibrary;
/// <summary>摄像头每拍到一帧画面时触发(教材 dll 里的委托名就是 CameraImage)</summary>
public delegate void CameraImage(ImageReadEvenArgs e);
public class ImageEventArgs : EventArgs { }
/// <summary>摄像头画面事件的参数;类名拼写与教材 dll 一致(EvenArgs)</summary>
public class ImageReadEvenArgs
{
public ImageEventArgs ImageEventArg { get; set; }
public Image img { get; set; }
}
/// <summary>
/// 网络摄像机。画面是自绘的东围墙场景(Camera/scene.svg 切出的帧):Pan 方法每次转动一格,
/// 实训台的红外对射被遮挡时画面里出现翻墙的人。和教材仿真版一样,ImageRead 在后台线程上定时触发。
/// </summary>
public class IPCameraHelper
{
// 与 Camera/build-frames.ts 一致:左右 7 档、上下 3 档,开始时在正中
private const int StepsX = 7;
private const int StepsY = 3;
private const int FrameIntervalMs = 250;
private static readonly string FramesDir = Path.Combine(Path.GetDirectoryName(typeof(IPCameraHelper).Assembly.Location)!, "Camera", "frames");
private static readonly Image?[] Frames = new Image?[StepsX * StepsY * 2];
private readonly object _lock = new();
private string? _ip;
private Timer? _timer;
private int _x = StepsX / 2;
private int _y = StepsY / 2;
private int _ticking;
private bool _errorReported;
public event CameraImage ImageRead;
/// <summary>连接摄像机。任何非空的 IP 都能连上(教材用 admin、空密码)</summary>
public void Open(string IpAdderss, string Uid, string Pwd) => _ip = IpAdderss;
/// <summary>开始传送画面;没有 Open 时不传</summary>
public void Start()
{
if (string.IsNullOrWhiteSpace(_ip)) return;
lock (_lock)
{
_timer ??= new Timer(_ => Tick());
_timer.Change(0, FrameIntervalMs);
}
SimHost.SendDevice("camera", "on", true);
}
public void Stop()
{
lock (_lock) _timer?.Change(Timeout.Infinite, Timeout.Infinite);
SimHost.SendDevice("camera", "on", false);
}
public void Close()
{
Stop();
_ip = null;
}
public void PanLeft() => Pan(-1, 0);
public void PanRight() => Pan(1, 0);
public void PanUp() => Pan(0, -1);
public void PanDown() => Pan(0, 1);
/// <summary>云台转动一格,到头后不再转;没有 Open 时无效</summary>
private void Pan(int dx, int dy)
{
if (string.IsNullOrWhiteSpace(_ip)) return;
int x, y;
lock (_lock)
{
_x = Math.Clamp(_x + dx, 0, StepsX - 1);
_y = Math.Clamp(_y + dy, 0, StepsY - 1);
(x, y) = (_x, _y);
}
SimHost.SendDevice("camera", "pan", new[] { x, y });
}
private void Tick()
{
// 上一帧的处理方法还没执行完时跳过这一帧
if (Interlocked.Exchange(ref _ticking, 1) == 1) return;
try
{
var handler = ImageRead;
if (handler == null) return;
int x, y;
lock (_lock) (x, y) = (_x, _y);
handler(new ImageReadEvenArgs { ImageEventArg = new ImageEventArgs(), img = Frame(x, y, TrainingBoard.ReadDigital(3)) });
}
catch (Exception ex)
{
// 教材仿真版用 System.Timers.Timer,处理方法里的异常不会让程序退出;这里报告一次,之后照常传画面
if (!_errorReported)
{
_errorReported = true;
SimHost.ReportException(ex);
}
}
finally
{
Volatile.Write(ref _ticking, 0);
}
}
/// <summary>同一位置的画面复用同一个 Image 对象:赋给 PictureBox 的是同一张图时不用重新发送</summary>
private static Image Frame(int x, int y, bool intruder)
{
var index = (y * StepsX + x) * 2 + (intruder ? 1 : 0);
lock (Frames)
{
return Frames[index] ??= Image.FromStream(new MemoryStream(File.ReadAllBytes(Path.Combine(FramesDir, $"{x}-{y}-{(intruder ? 1 : 0)}.jpg"))));
}
}
}
+4
View File
@@ -6,6 +6,10 @@
<RootNamespace>DeviceCtrlLibrary</RootNamespace>
<NoWarn>$(NoWarn);CS1591;CS8618;IDE1006</NoWarn>
</PropertyGroup>
<ItemGroup>
<!-- 网络摄像机的画面帧(由 Camera/build-frames.ts 生成),随运行器一起输出 -->
<None Include="Camera/frames/*.jpg" CopyToOutputDirectory="PreserveNewest" LinkBase="Camera/frames" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="../Sim.WinForms/Sim.WinForms.csproj" />
</ItemGroup>
+8
View File
@@ -41,6 +41,13 @@ internal static class ApiPolicy
["System.Runtime.InteropServices.NativeMemory"] = "调用本机代码",
};
/// <summary>不允许的类型里单独放行的成员:教材用 AppDomain.CurrentDomain.BaseDirectory 拼出保存照片的路径</summary>
private static readonly HashSet<string> AllowedMembers = new()
{
"System.AppDomain.CurrentDomain",
"System.AppDomain.BaseDirectory",
};
public static IEnumerable<Diagnostic> Check(CSharpCompilation compilation)
{
foreach (var tree in compilation.SyntaxTrees)
@@ -69,6 +76,7 @@ internal static class ApiPolicy
if (symbol is IDynamicTypeSymbol) return "dynamic 动态调用";
// using 指令里的命名空间不算:VS 生成的 AssemblyInfo.cs 会 using System.Runtime.InteropServices
if (symbol is INamespaceSymbol) return null;
if (symbol is IPropertySymbol && AllowedMembers.Contains($"{symbol.ContainingType.ToDisplayString()}.{symbol.Name}")) return null;
var type = symbol as INamedTypeSymbol ?? symbol.ContainingType;
// 方法的返回值、参数类型由调用处检查;这里看符号本身属于哪个类型
for (var t = type; t != null; t = t.ContainingType)
+24
View File
@@ -34,6 +34,8 @@ internal static class StudentProgramHost
CultureInfo.CurrentCulture = zhCN;
CultureInfo.CurrentUICulture = zhCN;
UseWritableBaseDirectory(dir);
var assembly = AssemblyLoadContext.Default.LoadFromStream(
new MemoryStream(File.ReadAllBytes(Path.Combine(dir, CompileServer.AssemblyFile))),
new MemoryStream(File.ReadAllBytes(Path.Combine(dir, CompileServer.PdbFile))));
@@ -81,6 +83,28 @@ internal static class StudentProgramHost
return 0;
}
/// <summary>
/// 学生程序的"程序所在目录":和在 VS 里按 F5 一样是工程下的 bin/Debug/,也是当前目录,可以写文件
/// (教材把摄像头照片存到 AppDomain.CurrentDomain.BaseDirectory + "Camera/")。
/// 沙箱里工程目录只读,改用沙箱自己的临时目录;两种情况下文件都在程序结束后清掉。
/// </summary>
private static void UseWritableBaseDirectory(string projectDir)
{
string baseDir;
try
{
baseDir = Directory.CreateDirectory(Path.Combine(projectDir, "bin", "Debug")).FullName;
}
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
{
baseDir = Directory.CreateDirectory(Path.Combine(Path.GetTempPath(), "StudentApp", "bin", "Debug")).FullName;
}
baseDir = Path.TrimEndingDirectorySeparator(baseDir) + Path.DirectorySeparatorChar;
AppContext.SetData("APP_CONTEXT_BASE_DIRECTORY", baseDir);
Directory.SetCurrentDirectory(baseDir);
SimHost.AppBaseDirectory = baseDir;
}
/// <summary>读取浏览器发来的操作,排队到界面线程执行</summary>
private static void ReadActions()
{
+105
View File
@@ -0,0 +1,105 @@
using System.ComponentModel;
using System.Drawing.Imaging;
using System.IO;
using System.Runtime.InteropServices;
using System.Security.Cryptography;
using Sim.Host;
namespace System.Drawing;
/// <summary>
/// 图片。System.Drawing 在 Linux 上不受支持,这里只保存图片文件的原始数据(JPEG、PNG、GIF、BMP)和尺寸:
/// 能显示在 PictureBox 上、保存成文件、从文件或流读回,不能逐像素绘制。
/// </summary>
public abstract class Image : IDisposable, ICloneable
{
private string? _simKey;
private protected Image(byte[] data)
{
Data = data;
(RawFormat, Width, Height) = ReadHeader(data) ?? throw new ArgumentException("参数无效:不是 JPEG、PNG、GIF 或 BMP 格式的图片。");
}
internal byte[] Data { get; }
public int Width { get; }
public int Height { get; }
public Size Size => new(Width, Height);
public ImageFormat RawFormat { get; }
public object? Tag { get; set; }
/// <summary>平台内部使用:图片内容的哈希,浏览器按它缓存图片,同一张图只传一次</summary>
[EditorBrowsable(EditorBrowsableState.Never)]
public string SimKey => _simKey ??= Convert.ToHexString(SHA1.HashData(Data)).ToLowerInvariant();
internal string MimeType => RawFormat.MimeType;
public static Image FromFile(string filename) => new Bitmap(filename);
public static Image FromStream(Stream stream) => new Bitmap(stream);
public void Save(string filename) => Save(filename, RawFormat);
/// <summary>按原格式写出图片数据(不做格式转换)。目录不存在时和 GDI+ 一样报"一般性错误"</summary>
public void Save(string filename, ImageFormat format)
{
try
{
File.WriteAllBytes(filename, Data);
}
catch (DirectoryNotFoundException)
{
throw new ExternalException("GDI+ 中发生一般性错误。(保存图片的文件夹不存在,先用 Directory.CreateDirectory 创建)");
}
SimHost.ImageSaved(Path.GetFullPath(filename), this);
}
public void Save(Stream stream, ImageFormat format) => stream.Write(Data, 0, Data.Length);
public object Clone() => new Bitmap(this);
public void Dispose() => GC.SuppressFinalize(this);
private static (ImageFormat, int, int)? ReadHeader(byte[] d)
{
if (d.Length >= 24 && d[0] == 0x89 && d[1] == 'P' && d[2] == 'N' && d[3] == 'G')
return (ImageFormat.Png, BigEndian(d, 16), BigEndian(d, 20));
if (d.Length >= 10 && d[0] == 'G' && d[1] == 'I' && d[2] == 'F')
return (ImageFormat.Gif, d[6] | d[7] << 8, d[8] | d[9] << 8);
if (d.Length >= 26 && d[0] == 'B' && d[1] == 'M')
return (ImageFormat.Bmp, BitConverter.ToInt32(d, 18), Math.Abs(BitConverter.ToInt32(d, 22)));
if (d.Length >= 4 && d[0] == 0xFF && d[1] == 0xD8)
{
// 依次跳过各段,找到记录尺寸的 SOF 段
var i = 2;
while (i + 9 < d.Length && d[i] == 0xFF)
{
var marker = d[i + 1];
var length = d[i + 2] << 8 | d[i + 3];
if (marker is >= 0xC0 and <= 0xCF and not 0xC4 and not 0xC8 and not 0xCC)
return (ImageFormat.Jpeg, d[i + 7] << 8 | d[i + 8], d[i + 5] << 8 | d[i + 6]);
i += 2 + length;
}
}
return null;
}
private static int BigEndian(byte[] d, int offset) => d[offset] << 24 | d[offset + 1] << 16 | d[offset + 2] << 8 | d[offset + 3];
}
public sealed class Bitmap : Image
{
public Bitmap(string filename) : base(File.ReadAllBytes(filename)) { }
public Bitmap(Stream stream) : base(ReadAll(stream)) { }
public Bitmap(Image original) : base(original.Data) { }
private static byte[] ReadAll(Stream stream)
{
using var buffer = new MemoryStream();
stream.CopyTo(buffer);
return buffer.ToArray();
}
}
@@ -0,0 +1,23 @@
namespace System.Drawing.Imaging;
/// <summary>图片格式。Image.Save 时只用来对应文件类型,不做格式转换</summary>
public sealed class ImageFormat
{
private readonly string _name;
private ImageFormat(string name, string mimeType)
{
_name = name;
MimeType = mimeType;
}
internal string MimeType { get; }
public static ImageFormat Jpeg { get; } = new("Jpeg", "image/jpeg");
public static ImageFormat Png { get; } = new("Png", "image/png");
public static ImageFormat Gif { get; } = new("Gif", "image/gif");
public static ImageFormat Bmp { get; } = new("Bmp", "image/bmp");
public static ImageFormat Icon { get; } = new("Icon", "image/x-icon");
public override string ToString() => _name;
}
+84
View File
@@ -0,0 +1,84 @@
using System.ComponentModel;
using System.Drawing;
using System.Text.Json.Nodes;
using Sim.Host;
namespace System.Windows.Forms;
public enum PictureBoxSizeMode { Normal, StretchImage, AutoSize, CenterImage, Zoom }
/// <summary>图片框(教材项目 4 显示摄像头画面)</summary>
public class PictureBox : Control, ISupportInitialize
{
private Image? _image;
private PictureBoxSizeMode _sizeMode;
private BorderStyle _borderStyle;
protected override Size DefaultSize => new(100, 50);
/// <summary>
/// 要显示的图片。不检查调用线程:教材在摄像头回调(后台线程)里直接给 Image 赋值,
/// 真实 WinForms 的 PictureBox 也不会因此报错。
/// </summary>
public Image? Image
{
get => _image;
set
{
LegacyThreads.CheckPoint();
if (ReferenceEquals(_image, value)) return;
_image = value;
NotifyChanged(nameof(Image), value);
if (_sizeMode == PictureBoxSizeMode.AutoSize) FitToImage();
}
}
public PictureBoxSizeMode SizeMode
{
get => _sizeMode;
set
{
if (SetProp(ref _sizeMode, value, nameof(SizeMode)) && value == PictureBoxSizeMode.AutoSize) FitToImage();
}
}
public BorderStyle BorderStyle
{
get => _borderStyle;
set => SetProp(ref _borderStyle, value, nameof(BorderStyle));
}
public string? ImageLocation { get; set; }
public Image? ErrorImage { get; set; }
public Image? InitialImage { get; set; }
public bool WaitOnLoad { get; set; }
/// <summary>从文件加载图片(只支持本地文件)</summary>
public void Load(string url)
{
ImageLocation = url;
Image = Image.FromFile(url);
}
public void Load()
{
if (!string.IsNullOrEmpty(ImageLocation)) Load(ImageLocation);
}
// Designer.cs 里 VS 生成 ((ISupportInitialize)pictureBox1).BeginInit() / EndInit()
public void BeginInit() { }
public void EndInit() { }
private void FitToImage()
{
if (_image != null) Size = _image.Size;
}
protected override void WriteProps(JsonObject props)
{
base.WriteProps(props);
props["Image"] = PropValue.From(_image);
props["SizeMode"] = _sizeMode.ToString();
props["BorderStyle"] = _borderStyle.ToString();
}
}
+1
View File
@@ -31,6 +31,7 @@ public static class PropValue
["underline"] = f.Underline,
["strikeout"] = f.Strikeout,
},
Image image => new JsonObject { ["key"] = SimHost.ImageKey(image), ["width"] = image.Width, ["height"] = image.Height },
Padding p => new JsonObject { ["left"] = p.Left, ["top"] = p.Top, ["right"] = p.Right, ["bottom"] = p.Bottom },
IEnumerable list => ListOf(list),
_ => JsonValueOf(value.ToString() ?? ""),
+36
View File
@@ -75,6 +75,42 @@ public static class SimHost
_output.WriteLine(new JsonObject { ["type"] = "patch", ["changes"] = changes }.ToJsonString(JsonOptions));
}
// ---------- 图片 ----------
private static readonly HashSet<string> SentImages = new();
/// <summary>
/// 学生程序的"程序所在目录"(AppDomain.CurrentDomain.BaseDirectory),可写,程序结束后清掉。
/// 运行器启动时设定;保存的图片按相对这里的路径显示在网页的照片列表里。
/// </summary>
public static string AppBaseDirectory { get; set; } = AppContext.BaseDirectory;
/// <summary>图片在浏览器端的编号;第一次用到时先把图片数据发过去,浏览器缓存后同一张图不再重发</summary>
public static string ImageKey(System.Drawing.Image image)
{
var key = image.SimKey;
bool isNew;
lock (SentImages) isNew = SentImages.Add(key);
if (isNew)
{
Send(new JsonObject
{
["type"] = "image",
["key"] = key,
["mime"] = image.MimeType,
["data"] = Convert.ToBase64String(image.Data),
});
}
return key;
}
/// <summary>学生程序用 Image.Save 保存了图片:网页的照片列表里显示出来</summary>
public static void ImageSaved(string fullPath, System.Drawing.Image image)
{
var path = fullPath.StartsWith(AppBaseDirectory, StringComparison.Ordinal) ? fullPath[AppBaseDirectory.Length..] : fullPath;
Send(new JsonObject { ["type"] = "imageSaved", ["path"] = path, ["image"] = ImageKey(image) });
}
public static void SendConsole(string text) => Send(new JsonObject { ["type"] = "console", ["text"] = text });
public static void SendDevice(string device, string action, object? data)