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

+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)