001package org.nasdanika.ai; 002 003import java.awt.image.BufferedImage; 004import java.io.File; 005import java.io.IOException; 006import java.io.InputStream; 007import java.net.URL; 008import java.util.function.Function; 009 010import javax.imageio.ImageIO; 011 012import reactor.core.publisher.Mono; 013 014public interface BufferedImageSimilarityComputer<S> extends SimilarityComputer<BufferedImage, S> { 015 016 default SimilarityComputer<InputStream,S> asInputStreamSimilarityComputer() { 017 Function<InputStream, Mono<BufferedImage>> mapper = in -> { 018 try { 019 return Mono.just(ImageIO.read(in)); 020 } catch (IOException e) { 021 throw new IllegalArgumentException("Cannot read image from input stream: " + e, e); 022 } 023 }; 024 025 return adapt(mapper); 026 } 027 028 default SimilarityComputer<URL,S> asUrlSimilarityComputer() { 029 Function<URL, Mono<BufferedImage>> mapper = url -> { 030 try { 031 return Mono.just(ImageIO.read(url)); 032 } catch (IOException e) { 033 throw new IllegalArgumentException("Cannot read image from '" + url + "': " + e, e); 034 } 035 }; 036 037 return adapt(mapper); 038 } 039 040 default SimilarityComputer<File,S> asFileSimilarityComputer() { 041 Function<File, Mono<BufferedImage>> mapper = file -> { 042 try { 043 return Mono.just(ImageIO.read(file)); 044 } catch (IOException e) { 045 throw new IllegalArgumentException("Cannot read image from '" + file.getAbsolutePath() + "': " + e, e); 046 } 047 }; 048 049 return adapt(mapper); 050 } 051 052}