I'm using omniauth-twitter gem to authenticate users through twitter. I am also using their Twitter profile image as their avatar for my site. However, the image I get from Twitter is low resolution. I know Twitter has better resolution pics available. How do I get it?
Here is what I am currently doing. It is a method in the user model. It works, just doesn't get me a good quality pic:
user.rb
def update_picture(omniauth)
self.picture = omniauth['info']['image']
end
I thought maybe I could pass a size option onto it somehow, but can not seem to find a good solution.
I'm using the omniauth-twitter gem as well. In the apply_omniauth method of my User model, I save the Twitter image path like this, stripping the _normal suffix:
if omniauth['provider'] == 'twitter'
self.image = omniauth['info']['image'].sub("_normal", "")
end
Then I have a helper method called portrait that accepts a size argument. As Terence Eden suggests, you can just replace the _size suffix of the filename to access the different image sizes that Twitter provides:
def portrait(size)
# Twitter
# mini (24x24)
# normal (48x48)
# bigger (73x73)
# original (variable width x variable height)
if self.image.include? "twimg"
# determine filetype
case
when self.image.downcase.include?(".jpeg")
filetype = ".jpeg"
when self.image.downcase.include?(".jpg")
filetype = ".jpg"
when self.image.downcase.include?(".gif")
filetype = ".gif"
when self.image.downcase.include?(".png")
filetype = ".png"
else
raise "Unable to read filetype of Twitter image for User ##{self.id}"
end
# return requested size
if size == "original"
return self.image
else
return self.image.gsub(filetype, "_#{size}#{filetype}")
end
end
end
Once you have the URL of the image, it's quite simple. You need to remove the "_normal" from the end of the URL.
Here's my avatar image
https://si0.twimg.com/profile_images/2318692719/7182974111_ec8e1fb46f_s_normal.jpg
Here's the larger version
https://si0.twimg.com/profile_images/2318692719/7182974111_ec8e1fb46f_s.jpg
A simple regex should suffice.
Remember, the size of the image is unpredictable - so you may wish to resize it before displaying it on your site.
A better way to do this is through the config options of the omniauth-twitter gem.
provider :twitter, "API_KEY", "API_SECRET", :image_size => 'original'
https://github.com/arunagw/omniauth-twitter
Related
I stored image file in path djangor_prject_name/pictures/image_name.jpg by using
models.ImageField(upload_to='pictures/services/', max_length=255, null=True, blank=True)
and file is uploaded successfully.
But while retrieving, what is the exact url to view image?
Because id Database, the value is just
picutes/services/image_name.jpg
So, in my view file, I am using vue.js and need full path or url of the image to display.
After creation it won't give you full url, but in the list it will come with full url. So for that you use custom serializers.SerializerMethodField.
class TestSerializer(serializers.ModelSerializer):
photo = serializers.SerializerMethodField()
class Meta:
model = Test
fields = ('photo',)
def get_photo(self, car):
request = self.context.get('request')
photo = Test.photo.url
return request.build_absolute_uri(photo)
For further details refer here
I have a model with a single field with carrierwave for file upload. I searched the google group but don't find a straightforward way to add file uploads to netzke component. I will be happy with doing it in a panel view with a regular browser file upload, i don't need anything fancy.
I just saw one of the demos has a file upload, the Paging form with custom layout. I think I still need guidance how to put it into the Basepack Grid
File upload field should first be added into Basepack::Form (which then can be tested independently):
class AttachmentForm < Netzke::Basepack::Form
def configure(c)
super
c.model = "Attachment"
c.items = [{xtype: :fileuploadfield, name: 'attachment'}]
end
end
Then your grid should be configured to use this form instead of the built-in one:
class AttachmentGrid < Netzke::Basepack::Grid
def configure(c)
super
c.model = 'Attachment'
c.force_fit = true
c.columns = [:link]
c.bbar = [:add_in_form, :del]
end
def preconfigure_record_window(c)
super
c.form_config.klass = AttachmentForm
c.width = 600
c.height = 150
end
end
For reference, here's also the Attachment model:
class Attachment < ActiveRecord::Base
mount_uploader :attachment
# this is a virtual column referred to from `AttachmentGrid`;
# can be moved over to grid itself using `getter` in case
# you object putting HTML into the model
def link
"<a href='#{attachment.url}' target='_blank'>#{attachment.file.try(:identifier)}</a>"
end
end
I am building an iOS app using Rubymotion.
I need to let the user snap a photo with the camera and then upload it to a Rails 3 backend (with Paperclip) using the BubbleWrap Http module (or any better?).
How can I do this?
This is my code:
controller = UIImagePickerController.alloc.init
controller.sourceType = UIImagePickerControllerSourceTypeCamera
controller.mediaTypes = [KUTTypeImage]
controller.allowsEditing = true
controller.delegate = self
self.navigationController.presentModalViewController(controller, animated:true)
This I use after taking the shot:
metadata = info.objectForKey(UIImagePickerControllerMediaMetadata)
the_image = info.objectForKey(UIImagePickerControllerOriginalImage)
image = view.viewWithTag 3
image.image = the_image
picker.dismissModalViewControllerAnimated(true)
This is my upload code:
data = {access_token: TOKEN, id: task, image: image}
BubbleWrap::HTTP.get("#{URL}#{project}/message", {payload: data}) do |response|
if response.ok?
json = BubbleWrap::JSON.parse(response.body)
if json['total'] > 0
infos = json['taskinfos'].map {|ej| self.from_json(ej["taskinfo"])}
block.call(true, infos)
else
block.call(false, nil)
end
else
block.call(false, nil)
end
end
Uploading images should be done via a POST request and not a GET request like you have done. Most web servers have a limit to how big a GET request can be, and it is usually 8k, read here for more info maximum length of HTTP GET request? , so it's not suitable for images.
Play around with bubble motion and look at the requests in the log files on the server to see what comes out. Try to make the request look like a request made from within rails itself, ie from a web page where you upload to the the controller.
So you could change the request to POST and let people know what error messages you get.
I'm looking for a library or command-line program that can compress PDFs.
Compression speed and file size are very important.
The PDFs are full of very large print-quality images.
Adobe Acrobat does high-quality, fast compression but does not allow "reduced size pdfs" to be saved through a programmatic interface.
Ghostscript does high-quality compression be takes way too long (minutes).
If a commercial library is an option, you could give Amyuni PDF Creator a try. There is .net version (C#/VB.Net etc) and an ActiveX version (for C++/Delphi/VB/PHP etc).
You can iterate through all the objects of each page, pick those who are images, and reduce their size. You have several possibilities there:
Setting a lower compression rate.
Down-sampling (extracting the image, re-sizing it to a lower
resolution, and putting it back in your file)
Combining the previous two.
Here is how the code would look like for the first option, in C#, using Amyuni PDF Creator .Net:
//open a pdf document
document.Open("c:\\temp\\myfile.pdf","");
IacPage page1 = document.GetPage (1);
Amyuni.PDFCreator.IacAttribute attribute = page1.AttributeByName ("Objects");
// listobj is an array list of graphic objects
System.Collections.ArrayList listobj = (System.Collections.ArrayList) attribute.Value;
foreach ( object pdfObj in listobj )
{
if ((IacObjectType)pdfObj.AttributeByName("ObjectType").Value == IacObjectType.acObjectTypePicture)
{
if ((IacImageCompressionConstants)pdfObj.AttributeByName("Compression").Value == IacImageCompressionConstants.acCompressionJPegMedium)
pdfObj.AttributeByName("Compression").Value = IacImageCompressionConstants.acCompressionJPegLow;
if ((IacImageCompressionConstants)pdfObj.AttributeByName("Compression").Value == IacImageCompressionConstants.acCompressionJPegHigh)
pdfObj.AttributeByName("Compression").Value = IacImageCompressionConstants.acCompressionJPegMedium;
// (...)
}
}
usual disclaimer applies
You might want to try Docotic.Pdf library for your task.
Here is a code that scales all images that have width or height greater or equal to 256. Scaled images are then encoded using JPEG compression with quality set to 65.
public static void RecompressToJpeg(string path, string outputPath)
{
using (PdfDocument doc = new PdfDocument(path))
{
foreach (PdfImage image in doc.Images)
{
// image that is used as mask or image with attached mask are
// not good candidates for recompression
if (!image.IsMask && image.Mask == null && (image.Width >= 256 || image.Height >= 256))
image.Scale(0.5, PdfImageCompression.Jpeg, 65);
}
doc.Save(outputPath);
}
}
You could also just recompress images without changing their sizes using one of the RecompressWithJpeg methods (or one of other RecompressXXX methods).
And images can be resized to specified width and height using one of the ResizeTo methods. Please note that you will need to take aspect ratio into account in the latter case.
Disclaimer: I work for the vendor of the library.
I would like to crop an image to the size the user has selected from a list (e.g. 100x100px, 200x200px,...)
How would I pass that attribute to the uploader or get the model's attribute from within the uploader?
Accessing the model's attribute from within the uploader as following does not work:
version :thumb do
thumbnail_size = model.thumbnail_size
...
...
end
I get following error:
undefined local variable or method `model' for #
Thank you!
Florian
In order to be able to access the model's attribute I had to add a manipulation helper.
class MyUploader < CarrierWave::Uploader::Base
...
version :thumb do
process :custom_thumbnail
process :convert => 'jpg'
...
end
def custom_thumbnail
width = model.get_image_width
height = model.get_image_height
manipulate! do |img|
img.convert "#{width}x#{height}"
img
end
end
end