MiniMagick can't write decoded Base64 image

dkershaw

I'm having trouble calling image.write with MiniMagick on a decoded base64 image in Rails. Every line seems to be working properly except for image.write. The code below is in my Rails API ImageController, which my React frontend is hitting through a POST request with the encoded image.

def create
    uploaded_io = params["image_io"]["base64"] # base64 string + metadata
    metadata = uploaded_io.split(',/')[0] + "," # "data:image/jpeg;base64,"
    filetype = metadata.split("/")[1].split("base64")[0][0...-1] # "jpeg"
    base64_string = uploaded_io[metadata.size..-1] # base64 string w/o metadata
    blob = Base64.decode64(base64_string)
    image = MiniMagick::Image.read(blob)
    image.write `#{Time.new.to_i}.#{filetype}` 

    storage = Google::Cloud::Storage.new(
        project_id: ENV['GOOGLE_CLOUD_PROJECT'],
        credentials: JSON.parse(File.read('config/google_cloud_credentials.json'))
    )

    bucket = storage.bucket "auto-stock-189103.appspot.com"
    bucket.create_file image,`test/#{Time.new.to_i}.jpg`
end

I added comments to the first few lines in the code describing their value. base64_string was too long to comment, so here is its value:

"/9j/4QAYRXhpZgAASUkqAAgAAAAAAAAAAAAAAP/sABFEdWNreQABAAQAAABkAAD/4QMtaHR0cDovL25zLmFkb2JlLmNvbS94YXAvMS4wLwA8P3hwYWNrZXQgYmVnaW49Iu+7vyIgaWQ9Ilc1TTBNcENlaGlIenJlU3pOVGN6a2M5ZCI/PiA8eDp4bXBtZXRhIHhtbG5zOng9ImFkb2JlOm5zOm1ldGEvIiB4OnhtcHRrPSJBZG9iZSBYTVAgQ29yZSA1LjMtYzAxMSA2Ni4xNDU2NjEsIDIwMTIvMDIvMDYtMTQ6NTY6MjcgICAgICAgICI+IDxyZGY6UkRGIHhtbG5zOnJkZj0iaHR0cDovL3d3dy53My5vcmcvMTk5OS8wMi8yMi1yZGYtc3ludGF4LW5zIyI+IDxyZGY6RGVzY3JpcHRpb24gcmRmOmFib3V0PSIiIHhtbG5zOnhtcD0iaHR0cDovL25zLmFkb2JlLmNvbS94YXAvMS4wLyIgeG1sbnM6eG1wTU09Imh0dHA6Ly9ucy5hZG9iZS5jb20veGFwLzEuMC9tbS8iIHhtbG5zOnN0UmVmPSJodHRwOi8vbnMuYWRvYmUuY29tL3hhcC8xLjAvc1R5cGUvUmVzb3VyY2VSZWYjIiB4bXA6Q3JlYXRvclRvb2w9IkFkb2JlIFBob3Rvc2hvcCBDUzYgKE1hY2ludG9zaCkiIHhtcE1NOkluc3RhbmNlSUQ9InhtcC5paWQ6MTNDQjQyRjlEQTAxMTFFN0E4N0VBNzdGODEwREFGMTYiIHhtcE1NOkRvY3VtZW50SUQ9InhtcC5kaWQ6MTNDQjQyRkFEQTAxMTFFN0E4N0VBNzdGODEwREFGMTYiPiA8eG1wTU06RGVyaXZlZEZyb20gc3RSZWY6aW5zdGFuY2VJRD0ieG1wLmlpZDoxM0NCNDJGN0RBMDExMUU3QTg3RUE3N0Y4MTBEQUYxNiIgc3RSZWY6ZG9jdW1lbnRJRD0ieG1wLmRpZDoxM0NCNDJGOERBMDExMUU3QTg3RUE3N0Y4MTBEQUYxNiIvPiA8L3JkZjpEZXNjcmlwdGlvbj4gPC9yZGY6UkRGPiA8L3g6eG1wbWV0YT4gPD94cGFja2V0IGVuZD0iciI/Pv/uAA5BZG9iZQBkwAAAAAH/2wCEAAEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQECAgICAgICAgICAgMDAwMDAwMDAwMBAQEBAQEBAgEBAgICAQICAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDA//AABEIAAoACgMBEQACEQEDEQH/xABNAAEBAAAAAAAAAAAAAAAAAAAACQEBAQEAAAAAAAAAAAAAAAAAAAkKEAEAAAAAAAAAAAAAAAAAAAAAEQEAAAAAAAAAAAAAAAAAAAAA/9oADAMBAAIRAxEAPwCMKU7f4AAA/9k="

Testing it here renders the correct image (a red square), but when I run the image.write line it returns the following error:

bin/rails: No such file or directory - 1513397345.jpeg
*** NoMethodError Exception: undefined method `write' for nil:NilClass
nil

Here's the return value of image = MiniMagick::Image.read(blob) for reference:

#<MiniMagick::Image:0x00007f9ba76ba1f8 @path="/var/folders/pf/xhvv11092_j08hw47q6rt9z80000gn/T/mini_magick20171215-26353-l2lcyu", @tempfile=#<Tempfile:/var/folders/pf/xhvv11092_j08hw47q6rt9z80000gn/T/mini_magick20171215-26353-l2lcyu (closed)>, @info=#<MiniMagick::Image::Info:0x00007f9ba76ba1d0 @path="/var/folders/pf/xhvv11092_j08hw47q6rt9z80000gn/T/mini_magick20171215-26353-l2lcyu", @info={}>>

Ultimately, my goal is to upload the image to Google Cloud so please let me know if there's a better way to go about this. I'm following this answer from a similar question, which is why I have it structured this way.

mu is too short

I think your problem is that you're using backticks where you mean to use double quotes:

image.write `#{Time.new.to_i}.#{filetype}` 
# ----------^----------------------------^

Backticks will attempt to execute their contents in the shell. You don't have an executable file named 1513397345.jpeg (which is what #{Time.new.to_i}.#{filetype} evaluates to) so you get an error.

You just want to use plain old double quotes to get the string interpolation you're expecting:

image.write "#{Time.new.to_i}.#{filetype}"

and again a few lines below that:

bucket.create_file image, "test/#{Time.new.to_i}.jpg"

Furthermore, you probably want to store that filename in a variable because Time.new.to_i isn't guaranteed to be the same in both invocation:

name = "#{Time.new.to_i}.#{filetype}
image.write name
#...
bucket.create_file image, name

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

Can't open image from Intent decoded from base64

How to write a base64 decoded png image to file?

Valid Base64 string can't be decoded

Validate a base64 decoded image in laravel

base64 'payload' string from rabbitmq queue can't be decoded properly

Can't redraw image represented in base64

Laravel File Storage: How to store (decoded) base64 image?

Base 64 Encoded QRGen QR code can't be decoded

base64 encoded string: can be decoded in PHP but not Java?

Why encode string with base64 if it can be easily decoded

Decoded Base64 to dataframe

Some utf-8 strings base64 encoded by php can not be decoded using iOS base64 library?

Why I can't insert a base64 encoded image into an e-mail HTML Velocity template?

Can't read Base64 encoded image in Node.js which is sent from Python

Can't get base64 resized image from javascript canvas

Boto3 + Django + S3 decoded base64 Image Upload not working

Can I filter on decoded UTF-8/Base64 in Thunderbird?

PHP imagecreatefromstring() doesn't work when i enter a base64 decoded value

NodeJS write base64 encoded image to file

Converted base64 image does not work, how can I get true base64 image?

Base64 decoded returning nil swift

How can I convert an image into a Base64 string?

How can I set Image source with base64

Can I download an image if it's in base64 format?

Can not get full image quality from base64 string

How can I sharpen base64 encoded image in php

Can I process base64 encoded image for watermark?

How can I use Base64 image paths in AppleScript?

How i can attach one base64 image in email?

TOP Ranking

  1. 1

    Failed to listen on localhost:8000 (reason: Cannot assign requested address)

  2. 2

    Loopback Error: connect ECONNREFUSED 127.0.0.1:3306 (MAMP)

  3. 3

    How to import an asset in swift using Bundle.main.path() in a react-native native module

  4. 4

    pump.io port in URL

  5. 5

    Compiler error CS0246 (type or namespace not found) on using Ninject in ASP.NET vNext

  6. 6

    BigQuery - concatenate ignoring NULL

  7. 7

    ngClass error (Can't bind ngClass since it isn't a known property of div) in Angular 11.0.3

  8. 8

    ggplotly no applicable method for 'plotly_build' applied to an object of class "NULL" if statements

  9. 9

    Spring Boot JPA PostgreSQL Web App - Internal Authentication Error

  10. 10

    How to remove the extra space from right in a webview?

  11. 11

    java.lang.NullPointerException: Cannot read the array length because "<local3>" is null

  12. 12

    Jquery different data trapped from direct mousedown event and simulation via $(this).trigger('mousedown');

  13. 13

    flutter: dropdown item programmatically unselect problem

  14. 14

    How to use merge windows unallocated space into Ubuntu using GParted?

  15. 15

    Change dd-mm-yyyy date format of dataframe date column to yyyy-mm-dd

  16. 16

    Nuget add packages gives access denied errors

  17. 17

    Svchost high CPU from Microsoft.BingWeather app errors

  18. 18

    Can't pre-populate phone number and message body in SMS link on iPhones when SMS app is not running in the background

  19. 19

    12.04.3--- Dconf Editor won't show com>canonical>unity option

  20. 20

    Any way to remove trailing whitespace *FOR EDITED* lines in Eclipse [for Java]?

  21. 21

    maven-jaxb2-plugin cannot generate classes due to two declarations cause a collision in ObjectFactory class

HotTag

Archive