Created
October 10, 2016 12:51
-
-
Save radzserg/8d4ec8bb8dd4698e1c4dd9ea5004bd64 to your computer and use it in GitHub Desktop.
Updates in image model
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| defmodule App.Image do | |
| # updates from part #1 | |
| # full image code https://gist.github.com/radzserg/3abc7a6fdac6fb98af8607d1b5a0cdaf | |
| alias App.Helpers.FileHelper | |
| alias App.Helpers.ImageHelper | |
| @doc """ | |
| Return resized image from parent image | |
| """ | |
| def resized_image(image, width, height) do | |
| case Repo.get_by(Image, parent_id: image.id, width: width, height: height) do | |
| nil -> create_resized_image(image, width, height) | |
| image -> image | |
| end | |
| end | |
| @doc """ | |
| Create imge from local file | |
| """ | |
| def create_from_file(path, type, filename \\ nil) do | |
| mime = FileHelper.get_mime!(path) | |
| size = FileHelper.get_size!(path) | |
| dest_path = if filename do | |
| build_path_from_path(path, type, filename) | |
| else | |
| build_path_from_path(path, type) | |
| end | |
| save_image_from_file(path, dest_path, mime, size, type) | |
| end | |
| _ = """ | |
| Creates resized image from given image | |
| """ | |
| defp create_resized_image(image, width, height) do | |
| upload_manager = App.Pact.get("upload_manager") | |
| base_path = Application.get_env(:app, App.Endpoint)[:root] | |
| local_path = "#{base_path}/runtime/resize_cache/" <> random_string(32) | |
| upload_manager.save_to_local_file!(image.path, local_path) | |
| ImageHelper.thumb(local_path, local_path, width, height) | |
| path = build_path_from_path(image.path, image.type) | |
| save_image_from_file(local_path, path, image.mime, image.size, image.type, image.id) | |
| end | |
| defp save_image_from_file(file, path, mime, size, type, parent_id \\ nil) do | |
| changeset = Image.changeset(%Image{}, %{path: path, mime: mime, | |
| size: size, type: type, parent_id: parent_id}) | |
| if changeset.valid? do | |
| upload_manager = App.Pact.get("upload_manager") | |
| case upload_manager.save_from_file!(file, path, %{content_type: mime}) do | |
| :ok -> | |
| case Repo.insert(changeset) do | |
| {:ok, image} -> {:ok, image} | |
| {:error, changeset} -> {:error, changeset} | |
| end | |
| {:error, reason} -> {:error, reason} | |
| end | |
| else | |
| {:error, changeset} | |
| end | |
| end | |
| end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment