Keep tall card portraits cropped to the card size (#77)

Add ChampionSource::card_portrait (Data Dragon loading art) and
Tracker::refresh_card_portraits, which downloads the missing ones, crops them
to the card's 0.68 aspect at the mockup's 24 % focus, shrinks them to
308 x 453 px and saves them as JPEG in portraits/cards via a .part file.
ChampionRow gains card_portrait.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
nessarandClaude Opus 5.5 committed 2026-11-20 21:08:57 +01:00
1 parent 34e8fb8a50
commit 50c0427958
8 files changed
+365 -2

No files matched your search

Generated
+1
View File
@@ -235,6 +235,7 @@ name = "arena-tracker-core"
version = "1.0.0"
dependencies = [
"base64 0.23.1",
"image",
"ring",
"rusqlite",
"rustls",
+1
View File
@@ -310,6 +310,7 @@ pub(crate) mod tests {
name: name.into(),
},
portrait: None,
card_portrait: None,
matches: 0,
best_placement: None,
top1: 0,
+1
View File
@@ -6,6 +6,7 @@ version.workspace = true
[dependencies]
base64 = { version = "0.23.1", default-features = false, features = ["std"] }
image = { version = "0.25", default-features = false, features = ["jpeg"] }
ring = "0.17.14"
rusqlite = { version = "0.43.0", features = ["bundled"] }
rustls = { version = "0.23.46", default-features = false, features = ["ring", "std", "tls12"] }
+180 -1
View File
@@ -1,6 +1,9 @@
use std::collections::BTreeMap;
use std::path::PathBuf;
use std::path::{Path, PathBuf};
use image::codecs::jpeg::JpegEncoder;
use image::imageops::{self, FilterType};
use image::{ExtendedColorType, ImageFormat, RgbImage};
use rusqlite::params;
use serde::Deserialize;
use ureq::Agent;
@@ -30,6 +33,8 @@ pub trait ChampionSource: Send + Sync {
fn catalog(&self, version: &str) -> Result<ChampionCatalog, SourceError>;
/// PNG bytes.
fn portrait(&self, version: &str, key: &str) -> Result<Vec<u8>, SourceError>;
/// JPEG bytes of the tall loading-screen art (308 x 560 px), used on the cards.
fn card_portrait(&self, key: &str) -> Result<Vec<u8>, SourceError>;
}
const HOST: &str = "https://ddragon.leagueoflegends.com";
@@ -73,6 +78,79 @@ impl ChampionSource for DataDragon {
);
get(&self.agent, &url, None, |b| b.read_to_vec())
}
fn card_portrait(&self, key: &str) -> Result<Vec<u8>, SourceError> {
// The loading art's path carries no game version.
let url = format!("{HOST}/cdn/img/champion/loading/{}_0.jpg", encode(key));
get(&self.agent, &url, None, |b| b.read_to_vec())
}
}
/// Width of a stored card portrait: the loading art's own width, about the largest card
/// at 150 % display scale. Together with `CARD_PORTRAIT_HEIGHT` it keeps the card's
/// aspect ratio (`CARD_ASPECT`), so the portraits stay at the cards' display size.
const CARD_PORTRAIT_WIDTH: u32 = 308;
/// Height of a stored card portrait: `CARD_PORTRAIT_WIDTH / CARD_ASPECT`, rounded.
const CARD_PORTRAIT_HEIGHT: u32 = 453;
/// A card's width / height (the mockup's `.card { aspect-ratio: .68 }`).
const CARD_ASPECT: f64 = 0.68;
/// Where the crop window sits in the overflow (the mockup's `object-position: 50% 24%`).
const CARD_FOCUS_X: f64 = 0.5;
const CARD_FOCUS_Y: f64 = 0.24;
const CARD_JPEG_QUALITY: u8 = 85;
/// Where a champion's card portrait is kept.
pub(crate) fn card_portrait_path(portraits_dir: &Path, key: &str) -> PathBuf {
portraits_dir.join("cards").join(format!("{key}.jpg"))
}
/// The crop window (x, y, width, height) that `object-fit: cover` with the card's
/// `object-position` shows of a `width` x `height` image.
fn card_crop(width: u32, height: u32) -> (u32, u32, u32, u32) {
let (w, h) = (f64::from(width), f64::from(height));
let (crop_w, crop_h) = if w / h < CARD_ASPECT {
// Taller than the card: keep the full width.
(width, ((w / CARD_ASPECT).round() as u32).clamp(1, height))
} else {
(((h * CARD_ASPECT).round() as u32).clamp(1, width), height)
};
let x = (CARD_FOCUS_X * f64::from(width - crop_w)).round() as u32;
let y = (CARD_FOCUS_Y * f64::from(height - crop_h)).round() as u32;
(
x.min(width - crop_w),
y.min(height - crop_h),
crop_w,
crop_h,
)
}
/// Crops the loading art to the card's shape, shrinks it to the stored size when larger
/// (never upscales) and encodes it as JPEG.
fn process_card_portrait(jpeg: &[u8]) -> Result<Vec<u8>, String> {
let art = image::load_from_memory_with_format(jpeg, ImageFormat::Jpeg)
.map_err(|e| format!("Portrait illisible : {e}"))?
.into_rgb8();
let (x, y, w, h) = card_crop(art.width(), art.height());
let mut card: RgbImage = imageops::crop_imm(&art, x, y, w, h).to_image();
drop(art);
if w > CARD_PORTRAIT_WIDTH {
card = imageops::resize(
&card,
CARD_PORTRAIT_WIDTH,
CARD_PORTRAIT_HEIGHT,
FilterType::Lanczos3,
);
}
let mut out = Vec::new();
JpegEncoder::new_with_quality(&mut out, CARD_JPEG_QUALITY)
.encode(
card.as_raw(),
card.width(),
card.height(),
ExtendedColorType::Rgb8,
)
.map_err(|e| format!("Portrait non encodable : {e}"))?;
Ok(out)
}
fn decode_latest_version(body: &str) -> Result<String, SourceError> {
@@ -164,6 +242,40 @@ impl Tracker {
Ok(())
}
/// Downloads the tall card portraits missing from the portraits dir's `cards` folder,
/// cropped and shrunk to the card's size (see `process_card_portrait`). A failed
/// download or an unreadable image is skipped and retried by the next pass. `on_saved`
/// is called after each portrait is saved. Meant to run after `refresh_champions`.
pub fn refresh_card_portraits(&self, on_saved: &mut dyn FnMut()) -> Result<(), Error> {
let Some((source, portraits_dir)) = &self.champions else {
return Ok(());
};
let cards_dir = portraits_dir.join("cards");
std::fs::create_dir_all(&cards_dir)
.map_err(|e| Error::Storage(format!("{} : {e}", cards_dir.display())))?;
for champion in self.cached_champions()? {
let path = card_portrait_path(portraits_dir, &champion.key);
// The key becomes a file name: only trust plain names.
if path.exists() || !champion.key.chars().all(|c| c.is_ascii_alphanumeric()) {
continue;
}
let Ok(art) = source.card_portrait(&champion.key) else {
continue;
};
let Ok(card) = process_card_portrait(&art) else {
continue;
};
// Written under another name first so a cut write is never taken for a portrait.
let partial = path.with_extension("part");
if std::fs::write(&partial, card).is_ok() && std::fs::rename(&partial, &path).is_ok() {
on_saved();
} else {
let _ = std::fs::remove_file(&partial);
}
}
Ok(())
}
pub(crate) fn cached_champions(&self) -> Result<Vec<Champion>, Error> {
let db = self.db();
let mut stmt = db.prepare("SELECT id, key, name FROM champions")?;
@@ -238,6 +350,73 @@ mod tests {
assert_eq!(champion(62).name, "Wukong");
}
/// A 308 x 560-like JPEG: red above `red_to`, green from `green_from`, blue between.
fn banded_jpeg(width: u32, height: u32, red_to: u32, green_from: u32) -> Vec<u8> {
let img = RgbImage::from_fn(width, height, |_, y| {
if y < red_to {
image::Rgb([255, 0, 0])
} else if y >= green_from {
image::Rgb([0, 255, 0])
} else {
image::Rgb([0, 0, 255])
}
});
let mut out = Vec::new();
JpegEncoder::new_with_quality(&mut out, 95)
.encode(img.as_raw(), width, height, ExtendedColorType::Rgb8)
.unwrap();
out
}
fn decoded(jpeg: &[u8]) -> RgbImage {
image::load_from_memory_with_format(jpeg, ImageFormat::Jpeg)
.unwrap()
.into_rgb8()
}
#[test]
fn the_crop_keeps_the_full_width_and_the_mockups_focus() {
assert_eq!(CARD_PORTRAIT_HEIGHT, (308.0 / CARD_ASPECT).round() as u32);
// 24 % of the 107 px overflow.
assert_eq!(card_crop(308, 560), (0, 26, 308, 453));
assert_eq!(card_crop(616, 1120), (0, 51, 616, 906));
// Wider than a card: the full height, centered.
assert_eq!(card_crop(500, 400), (114, 0, 272, 400));
// Already the card's shape.
assert_eq!(card_crop(68, 100), (0, 0, 68, 100));
}
#[test]
fn the_loading_art_is_cropped_to_the_card_at_the_focus() {
// The window is rows 26..479: red above it, green below it.
let card = process_card_portrait(&banded_jpeg(308, 560, 26, 479)).unwrap();
let card = decoded(&card);
assert_eq!((card.width(), card.height()), (308, 453));
for y in [10, 226, 442] {
let [r, g, b] = card.get_pixel(150, y).0;
assert!(b > 200 && r < 60 && g < 60, "row {y}: {r} {g} {b}");
}
}
#[test]
fn a_larger_art_is_shrunk_and_a_smaller_one_is_cropped_only() {
let large = decoded(&process_card_portrait(&banded_jpeg(616, 1120, 51, 957)).unwrap());
assert_eq!((large.width(), large.height()), (308, 453));
let small = decoded(&process_card_portrait(&banded_jpeg(100, 200, 0, 200)).unwrap());
assert_eq!((small.width(), small.height()), (100, 147));
}
#[test]
fn an_undecodable_art_is_an_error() {
assert!(process_card_portrait(b"pas une image").is_err());
assert!(process_card_portrait(&[]).is_err());
let mut cut = banded_jpeg(308, 560, 26, 479);
cut.truncate(cut.len() / 2);
let _ = process_card_portrait(&cut); // Must not panic; a cut file may still decode partly.
}
#[test]
fn rejects_a_non_numeric_champion_key() {
let body = r#"{"data":{"X":{"id":"X","key":"abc","name":"X"}}}"#;
+6 -1
View File
@@ -4,7 +4,7 @@ use std::collections::{BTreeMap, HashMap, HashSet};
use std::ops::Range;
use std::path::PathBuf;
use crate::champions::Champion;
use crate::champions::{Champion, card_portrait_path};
use crate::date::Date;
use crate::error::Error;
use crate::model::{Format, Match};
@@ -59,6 +59,8 @@ pub struct ChampionRow {
pub champion: Champion,
/// Only when the file exists in the portraits dir.
pub portrait: Option<PathBuf>,
/// Only when the file exists in the portraits dir's `cards` folder.
pub card_portrait: Option<PathBuf>,
// In scope (Season and Format filter):
pub matches: usize,
pub best_placement: Option<u8>,
@@ -326,6 +328,7 @@ pub(crate) fn compute(
};
ChampionRow {
portrait: None,
card_portrait: None,
matches: mine.len(),
best_placement: mine.iter().map(|m| m.placement).min(),
top1: mine.iter().filter(|m| m.placement == 1).count(),
@@ -435,6 +438,8 @@ impl Tracker {
for row in &mut stats.rows {
let path = dir.join(format!("{}.png", row.champion.key));
row.portrait = path.is_file().then_some(path);
let card = card_portrait_path(dir, &row.champion.key);
row.card_portrait = card.is_file().then_some(card);
}
}
Ok(stats)
+132
View File
@@ -170,6 +170,138 @@ fn portraits_are_downloaded_and_exposed_and_a_failed_one_is_left_out() {
assert!(!portraits.join("Jinx.part").exists());
}
fn cards_dir(dir: &std::path::Path) -> std::path::PathBuf {
dir.join("portraits").join("cards")
}
fn card_files(dir: &std::path::Path) -> Vec<String> {
let mut names: Vec<String> = std::fs::read_dir(cards_dir(dir))
.unwrap()
.map(|e| e.unwrap().file_name().into_string().unwrap())
.collect();
names.sort();
names
}
#[test]
fn a_missing_card_portrait_is_downloaded_once_then_read_from_disk() {
let dir = tempfile::tempdir().unwrap();
let source = FakeChampions::new("1.0", &CATALOG);
let calls = source.card_counter();
let tracker = reopen(dir.path(), source);
tracker.refresh_champions().unwrap();
assert!(
statistics(&tracker)
.rows
.iter()
.all(|r| r.card_portrait.is_none())
);
let mut saved = 0;
tracker.refresh_card_portraits(&mut || saved += 1).unwrap();
assert_eq!((saved, calls.load(Ordering::SeqCst)), (6, 6));
let stats = statistics(&tracker);
for row in &stats.rows {
let path = cards_dir(dir.path()).join(format!("{}.jpg", row.champion.key));
assert_eq!(row.card_portrait.as_ref(), Some(&path));
let card = image::open(&path).unwrap();
// The 40 x 60 art is smaller than a card: cropped to the card's shape, not enlarged.
assert_eq!((card.width(), card.height()), (40, 59));
}
let mut saved_again = 0;
tracker
.refresh_card_portraits(&mut || saved_again += 1)
.unwrap();
assert_eq!((saved_again, calls.load(Ordering::SeqCst)), (0, 6));
}
#[test]
fn a_failed_card_download_leaves_no_file_and_the_next_pass_resumes() {
let dir = tempfile::tempdir().unwrap();
let source = FakeChampions::new("1.0", &CATALOG);
let failure = source.card_failure();
let calls = source.card_counter();
let tracker = reopen(dir.path(), source);
tracker.refresh_champions().unwrap();
failure.store(true, Ordering::SeqCst);
let mut saved = 0;
tracker.refresh_card_portraits(&mut || saved += 1).unwrap();
assert_eq!(saved, 0);
assert!(card_files(dir.path()).is_empty());
assert!(
statistics(&tracker)
.rows
.iter()
.all(|r| r.card_portrait.is_none())
);
failure.store(false, Ordering::SeqCst);
tracker.refresh_card_portraits(&mut || saved += 1).unwrap();
assert_eq!(saved, 6);
assert_eq!(card_files(dir.path()).len(), 6);
assert_eq!(calls.load(Ordering::SeqCst), 12);
assert!(
statistics(&tracker)
.rows
.iter()
.all(|r| r.card_portrait.is_some())
);
}
#[test]
fn a_card_portrait_that_cannot_be_read_is_skipped_without_a_file() {
let dir = tempfile::tempdir().unwrap();
let tracker = reopen(
dir.path(),
FakeChampions::new("1.0", &CATALOG).with_card_art(b"<html>erreur</html>".to_vec()),
);
tracker.refresh_champions().unwrap();
let mut saved = 0;
tracker.refresh_card_portraits(&mut || saved += 1).unwrap();
assert_eq!(saved, 0);
assert!(card_files(dir.path()).is_empty());
}
#[test]
fn one_failed_card_portrait_does_not_stop_the_others() {
let dir = tempfile::tempdir().unwrap();
let tracker = reopen(
dir.path(),
FakeChampions::new("1.0", &CATALOG).without_portrait("Jinx"),
);
tracker.refresh_champions().unwrap();
let mut saved = 0;
tracker.refresh_card_portraits(&mut || saved += 1).unwrap();
assert_eq!(saved, 5);
assert!(!card_files(dir.path()).contains(&"Jinx.jpg".to_string()));
let stats = statistics(&tracker);
let jinx = stats
.rows
.iter()
.find(|r| r.champion.key == "Jinx")
.unwrap();
assert_eq!(jinx.card_portrait, None);
}
#[test]
fn refreshing_card_portraits_without_a_champion_source_does_nothing() {
let dir = tempfile::tempdir().unwrap();
let tracker = open_tracker(dir.path(), &[]);
tracker.refresh_card_portraits(&mut || {}).unwrap();
assert!(!dir.path().join("portraits").exists());
}
#[test]
fn refreshing_without_a_champion_source_does_nothing() {
let dir = tempfile::tempdir().unwrap();
+43
View File
@@ -355,6 +355,21 @@ pub struct FakeChampions {
failing: bool,
no_portrait: Vec<String>,
catalog_calls: Arc<AtomicUsize>,
/// What every card portrait download delivers.
card_art: Vec<u8>,
/// The card portrait downloads fail while this is set.
card_failure: Arc<AtomicBool>,
card_calls: Arc<AtomicUsize>,
}
/// A small valid JPEG, tall like the loading art (40 x 60 px).
pub fn card_art() -> Vec<u8> {
let img = image::RgbImage::from_fn(40, 60, |x, y| image::Rgb([x as u8 * 6, y as u8 * 4, 90]));
let mut out = Vec::new();
image::codecs::jpeg::JpegEncoder::new(&mut out)
.encode(img.as_raw(), 40, 60, image::ExtendedColorType::Rgb8)
.unwrap();
out
}
impl FakeChampions {
@@ -373,9 +388,28 @@ impl FakeChampions {
failing: false,
no_portrait: Vec::new(),
catalog_calls: Arc::default(),
card_art: card_art(),
card_failure: Arc::default(),
card_calls: Arc::default(),
}
}
/// Every card portrait download delivers these bytes.
pub fn with_card_art(mut self, bytes: Vec<u8>) -> FakeChampions {
self.card_art = bytes;
self
}
/// Set it to make the card portrait downloads fail (and clear it to let them succeed).
pub fn card_failure(&self) -> Arc<AtomicBool> {
self.card_failure.clone()
}
/// Card portrait downloads attempted.
pub fn card_counter(&self) -> Arc<AtomicUsize> {
self.card_calls.clone()
}
/// Every call fails with a network error.
pub fn failing(mut self) -> FakeChampions {
self.failing = true;
@@ -423,6 +457,15 @@ impl ChampionSource for FakeChampions {
}
Ok(format!("png of {key}").into_bytes())
}
fn card_portrait(&self, key: &str) -> Result<Vec<u8>, SourceError> {
self.card_calls.fetch_add(1, Ordering::SeqCst);
self.check()?;
if self.card_failure.load(Ordering::SeqCst) || self.no_portrait.iter().any(|k| k == key) {
return Err(SourceError::Network("coupé".into()));
}
Ok(self.card_art.clone())
}
}
// Statistics scenarios: a small catalog, two Seasons and Matches described by champion and Placement.
+1
View File
@@ -422,6 +422,7 @@ fn bare_row(name: &str, id: u32) -> ChampionRow {
name: name.into(),
},
portrait: None,
card_portrait: None,
matches: 0,
best_placement: None,
top1: 0,