In my Rails app, I have a form that allows users to upload images. My app is supposed to resize the images with the following controller method. (POST to this method, params[:file] contains the ActionDispatch::Http::UploadedFile that was uploaded:
def resize_and_store
file = params[:file]
# resize image
Magick::Image.read(file.tempfile).first
newimg = image.resize(100,100)
#etc... Store newimg
end
I get the following error, on the line that says Image.read:
Magick::ImageMagickError (no decode delegate for this image format `0xb9f6052c>' # error/constitute.c/ReadImage/544):
Testing this with an uploaded PNG file, it seems RMagick doesn't pick up that the temporary file is a PNG file. The code above does work if I read a locally stored PNG file, so it can't be that I'm missing the PNG decoder. How can I fix this and why does this happen?
You can do from_blob on a ActionDispatch::Http::UploadedFile param (this is how a file comes in):
images = Magick::Image.from_blob(params[:file].read)
Storing the file temporarily will solve the problem:
open('temp.png', 'wb') do |file|
file << uploaded.tempfile.read
end
images=Magick::Image.read('temp.png')
Probably wise to check input size as well.
Alternatively, parse the image from a blob.
Using the answer by #joost (or similar approach) really helped to point me in the right direction but it didn't work on the second attempt with the same temp file - my use case was creating multiple image types from the tempfile source. This is what I've used, wrapping in a File.open block so we don't leak the file descriptor:
File.open(tempfile, "rb") do |f|
img = Magick::Image::from_blob(f.read).first
resized = img.resize_to_fit(w, h)
resized.write(dest)
resized.destroy!
img.destroy!
end
Maybe there's something wrong with the form? You can consult with Rails Guide here:
Rails Guides: Uploading Files
I think that you may have multipart: true missing in your form declaration.
Also, I would strongly advise to use Carrierwave to handle file uploads. Among several things, it will help you to organize your file transformations (putting logic out of the controllers). Here's a railscast about it:
RailsCasts: CarrierWave File Uploads.
Good luck!
Related
I'm building a feature that parses a PDF format CV. I have a method that is called on :before_save which handles parsing. I'm able to access the PDF file within this method, before it saves using...
file = cv.queued_for_write[:original]
But then I need to pass the file to PDF::Reader, however, it seems like pdf-reader only accepts paths or URLs to files, not the actual file itself. This approach...
reader = PDF::Reader.new(file)
Throws this error:
ArgumentError (input must be an IO-like object or a filename):
Do I need to save the file to a tmp folder or something and then pass the path to the pdf-reader to parse it? I'm hoping to parse the PDF as quickly as possible, so that doesn't seem ideal. Any advice is appreciated!
I figured out that the "queued_for_write" object has a path attribute.
file = cv.queued_for_write[:original]
So I can just access it like this:
reader = PDF::Reader.new(file.path)
I am trying to upload a file in rails (using paperclip), and I want to process some of the file data before letting paperclip send it off to s3 storage. In my controller, I just grab the file parameter (which does give me a file) and then I try to read the lines into an array
csv_file = params[:activity][:data]
array = IO.readlines(csv_file.path)
The problem is, I'm only getting the last line of the file. I tried using .rewind, but still get just the last line.
I dislike readlines and I always use regular expressions. Try this.
End of line - \n
Handy block structure to ensure that the file handle is closed:
File.open(csv_file.path) do |f|
a = f.readlines
process a...
end
Reading a whole file into memory might not be a good idea depending on the size of the files.
I have an Attachment model, which is using Paperclip to handle uploaded files. The file can be anything an image, a txt, doc, pdf, rar, zip, tar etc.
I want to create thumbnails only if the file uploaded is an image.
How to create thumbnails in Paperclip conditionally based upon file content_type
This is a nice solution:
before_post_process :image?
def image?
!(data_content_type =~ /^image.*/).nil?
end
You can also use the image? method in your views to either render an image_tag, or something else...
I'd like to take a PDF file and convert it to images, each PDF page becoming a separate image.
"Convert a .doc or .pdf to an image and display a thumbnail in Ruby?" is a similar post, but it doesn't cover how to make separate images for each page.
Using RMagick itself, you can create images for different pages:
require 'RMagick'
pdf_file_name = "test.pdf"
im = Magick::Image.read(pdf_file_name)
The code above will give you an array arr[], which will have one entry for corresponding pages. Do this if you want to generate a JPEG image of the fifth page:
im[4].write(pdf_file_name + ".jpg")
But this will load the entire PDF, so it can be slow.
Alternatively, if you want to create an image of the fifth page and don't want to load the complete PDF file:
require 'RMagick'
pdf_file_name = "test.pdf[5]"
im = Magick::Image.read(pdf_file_name)
im[0].write(pdf_file_name + ".jpg")
ImageMagick can do that with PDFs. Presumably RMagick can do it too, but I'm not familiar with it.
The code from the post you linked to:
require 'RMagick'
pdf = Magick::ImageList.new("doc.pdf")
pdf is an ImageList object, which according to the documentation delegates many of its methods to Array. You should be able to iterate over pdf and call write to write the individual images to files.
Since I can't find a way to deal with PDFs on a per-page basis in RMagick, I'd recommend first splitting the PDF into pages with pdftk's burst command, then dealing with the individual pages in RMagick. This is probably less performant than an all-in-one solution, but unfortunately no all-in-one solution presents itself.
There's also PDF::Toolkit for Ruby that hooks into pdftk but I've never used it.
When I using "file_field" to upload a file:
The file name can be obtained in the controller:
params[:upload]['datafile'].original_filename
but how can I obtain the size and type of the file?
Use the content_type and size helper functions
params[:upload]['datafile'].content_type
Not sure why you'd want to do that in a controller, but any validation needs to be moved inside your model. Also try using a plugin like Paperclip or SWFUpload to handle uploads, for greater flexibility.
Try these links for a examples Paperclip, Attachment_fu, SWFUpload