feat: 截图功能验证。
截图需要 700 ms,转换成 webp 3 s。
This commit is contained in:
82
src-tauri/src/main.rs
Normal file
82
src-tauri/src/main.rs
Normal file
@@ -0,0 +1,82 @@
|
||||
#![cfg_attr(
|
||||
all(not(debug_assertions), target_os = "windows"),
|
||||
windows_subsystem = "windows"
|
||||
)]
|
||||
|
||||
use bmp::{Image, Pixel};
|
||||
use scrap::{Capturer, Display};
|
||||
use std::io::ErrorKind::WouldBlock;
|
||||
use std::path::Path;
|
||||
use std::thread;
|
||||
use std::time::Duration;
|
||||
use std::{fs, time::Instant};
|
||||
|
||||
// Learn more about Tauri commands at https://tauri.app/v1/guides/features/command
|
||||
#[tauri::command]
|
||||
fn greet(name: &str) -> String {
|
||||
format!("Hello, {}! You've been greeted from Rust!", name)
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
fn take_snapshot() -> String {
|
||||
let one_second = Duration::new(1, 0);
|
||||
let one_frame = one_second / 60;
|
||||
|
||||
let display = Display::primary().expect("Couldn't find primary display.");
|
||||
let mut capturer = Capturer::new(display).expect("Couldn't begin capture.");
|
||||
let (w, h) = (capturer.width(), capturer.height());
|
||||
|
||||
loop {
|
||||
// Wait until there's a frame.
|
||||
|
||||
let start = Instant::now();
|
||||
let buffer = match capturer.frame() {
|
||||
Ok(buffer) => buffer,
|
||||
Err(error) => {
|
||||
if error.kind() == WouldBlock {
|
||||
// Keep spinning.
|
||||
thread::sleep(one_frame);
|
||||
continue;
|
||||
} else {
|
||||
panic!("Error: {}", error);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
println!("Captured! Saving...");
|
||||
|
||||
// Flip the ARGB image into a BGRA image.
|
||||
|
||||
let mut bitflipped = Vec::with_capacity(w * h * 3);
|
||||
let stride = buffer.len() / h;
|
||||
|
||||
let mut img = Image::new(w as u32, h as u32);
|
||||
|
||||
for y in 0..h {
|
||||
for x in 0..w {
|
||||
let i = stride * y + 4 * x;
|
||||
bitflipped.extend_from_slice(&[buffer[i + 2], buffer[i + 1], buffer[i]]);
|
||||
// img.set_pixel(
|
||||
// x as u32,
|
||||
// y as u32,
|
||||
// Pixel::new(buffer[i + 2], buffer[i + 1], buffer[i]),
|
||||
// );
|
||||
}
|
||||
}
|
||||
|
||||
let webp_memory =
|
||||
webp::Encoder::from_rgb(bitflipped.as_slice(), w as u32, h as u32).encode(100.0);
|
||||
let encode_text = base64::encode(&*webp_memory);
|
||||
// let output_path = Path::new("assets").join("lake").with_extension("webp");
|
||||
// std::fs::write(&output_path, &*webp_memory).unwrap();
|
||||
println!("运行耗时: {:?}", start.elapsed());
|
||||
return encode_text;
|
||||
}
|
||||
}
|
||||
|
||||
fn main() {
|
||||
tauri::Builder::default()
|
||||
.invoke_handler(tauri::generate_handler![greet, take_snapshot])
|
||||
.run(tauri::generate_context!())
|
||||
.expect("error while running tauri application");
|
||||
}
|
Reference in New Issue
Block a user