Skip to content

Commit

Permalink
Support converting images to JPEG without resizing
Browse files Browse the repository at this point in the history
  • Loading branch information
Sija committed Feb 19, 2024
1 parent 59cf689 commit 4799222
Show file tree
Hide file tree
Showing 3 changed files with 16 additions and 11 deletions.
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@ REST web API for the [libgphoto2](http://www.gphoto.org/) library. You can use i

#### `/cameras/:id/blob`

- `GET /cameras/:id/blob/*filepath[?width=512&height=768]`
- `GET /cameras/:id/blob/*filepath[?as_jpeg=true&width=512&height=768]`
- `DELETE /cameras/:id/blob/*filepath`

#### `/cameras/:id/zip`
Expand Down
20 changes: 12 additions & 8 deletions src/ext/kemal.cr
Original file line number Diff line number Diff line change
Expand Up @@ -45,18 +45,22 @@ end

private MAGICKLOAD_EXTENSIONS = %w(.arw .cin .cr2 .crw .nef .orf .raf .x3f)

def send_file(env, file : GPhoto2::CameraFile, width : Int, height : Int? = nil, disposition = "inline")
if Path[file.name].extension.downcase.in?(MAGICKLOAD_EXTENSIONS)
def send_file_as_jpeg(env, file : GPhoto2::CameraFile, width : Int? = nil, height : Int? = nil, disposition = "inline")
file_path = Path[file.path]

if file_path.extension.downcase.in?(MAGICKLOAD_EXTENSIONS)
image, _ = Vips::Image.magickload_buffer(file.to_slice)
else
image = Vips::Image.new_from_buffer(file.to_slice)
end

image = image.thumbnail_image(
width: width,
height: height,
size: Vips::Enums::Size::Down
)
if width
image = image.thumbnail_image(
width: width,
height: height,
size: Vips::Enums::Size::Down,
)
end

restore_headers_on_exception(env.response) do |response|
if info = file.info.file?
Expand All @@ -68,7 +72,7 @@ def send_file(env, file : GPhoto2::CameraFile, width : Int, height : Int? = nil,

send_file env, image.jpegsave_buffer(strip: true),
mime_type: "image/jpeg",
filename: "#{Path[file.name].stem}.jpg",
filename: "#{file_path.stem}.jpg",
disposition: disposition
end
end
Expand Down
5 changes: 3 additions & 2 deletions src/gphoto2/web/routes.cr
Original file line number Diff line number Diff line change
Expand Up @@ -132,15 +132,16 @@ get "/cameras/:id/blob/*filepath" do |env|
filepath = env.params.url["filepath"]
path = Path.posix(filepath)

as_jpeg = env.params.query["as_jpeg"]? == "true"
width = env.params.query["width"]?.try(&.to_i)
height = env.params.query["height"]?.try(&.to_i)

GPhoto2::Web.camera_by_id(id) do |camera|
fs = camera / path.dirname
file = fs.open(path.basename)

if width
send_file env, file,
if as_jpeg || width
send_file_as_jpeg env, file,
width: width,
height: height
else
Expand Down

0 comments on commit 4799222

Please sign in to comment.