How to retrieve an URL from an API response object from Cloudinary JAVA - cloudinary

i am developing a web app using Java. I deployed my app to Heroku. In Heroku i am using an Add-on called Cloudinary to store my pictures in cloud, and retrieve them when needed. I am using the search api to retrieve a picture from the cloudinary cloud, but i can't manage to access the url from the response api. Below is my Java code:
String nameOfPicture = nameOfRecipe;
Cloudinary cloudinary = null;
try {
cloudinary = new Cloudinary(String.valueOf(new URI(System.getenv("CLOUDINARY_URL"))));
} catch (URISyntaxException e) {
System.err.println(e);
}
String imgUrl = null;
try {
ApiResponse result = cloudinary.search()
.expression(nameOfPicture)
.maxResults(10)
.execute();
System.out.println(result.get("resources"));
System.out.println(result.get("url"));
} catch (Exception e) {
System.err.println(e);
}
If i System.out.println(result.get("resources")) i can see there is a response from cloudinary like this:
[{
aspect_ratio = 1.77778,
access_control = null,
format = jpg,
resource_type = image,
secure_url = https: //res.cloudi nary.com/...../POULTRY/ACAPULCO_CHICKEN.jpg, created_at=2020-12-15T18:12:39+00:00, backup_bytes=0, type=upload, ve rsion=1608055959, access_mode=public, created_by={access_key=..., external_id=......}, url=http://res.cloudinary.com /...../v1608055959/FOOD_IMG/POULTRY/ACAPULCO_CHICKEN.jpg, public_id=FOOD_IMG/POULTRY/ACAPULCO_CHICKEN, uploaded_by={access_key=....... .., external_id=.......}, folder=FOOD_IMG/..., filename=...., pixels=360000, uploaded_at=2020-12-15T18:12:39
+00: 00,
bytes = 131330,
width = 800,
etag = ce45a927d98e07e1c73bd16030218f96,
height = 450,
status = active
}, {
aspect_ratio = 0.66667,
access_control = null,
format = j pg,
resource_type = image,
secure_url = https: //res.cloudinary.com/...../FOOD_IMG/POULTRY/ADOBO_CHICKEN_GINGER.jpg, created_at= 2020-12-15T16:40:52+00:00, backup_bytes=0, type=upload, version=1608050452, access_mode=public, created_by={access_key=....., external_id=.......}, url=http://res.cloudinary.com/hmzve6z5z/image/upload/..../POULTRY/ADOBO_CHICKEN_GINGER.jpg, public_id=FOOD_ IMG/POULTRY/ADOBO_CHICKEN_GINGER, uploaded_by={access_key=...., external_id=......}, folder=FOOD_IMG/POULTRY, filenam e=ADOBO_CHICKEN_GINGER, pixels=960000, uploaded_at=2020-12-15T16:40:52+00:00, bytes=242816, width=800, etag=......d, height=120 0, status=active}]
Question is, how can i acces and retrieve the url of the picture from this response ?
Thank you!

The response is a JSON object and you can loop over it and grab the secure_url.
JSONArray jsonArray = outerObject.getJSONArray("resources");
for (int i = 0, size = jsonArray.length(); i < size; i++) {
JSONObject objectInArray = jsonArray.getJSONObject(i);
String secure_url=objectInArray.get("secure_url").toString();
}

Related

SixLabors.ImageSharp Compressing image is making the image bigger as a byte

I have compress method which is uses SixLabors.ImageSharp. When i compress a image on that method, its getting more size before then i upload it. The image i upload is 2,03 mb
and when its come out from the compression method, its getting like that 4,54 mb
and here it's my compression method :
public async Task<FileRepo> FileUploadToDatabase(List<IFormFile> files)
{
foreach (var file in files)
{
var fileName = Path.GetFileNameWithoutExtension(file.FileName);
var fileExtension = Path.GetExtension(file.FileName);
using var image = Image.Load(file.OpenReadStream());
IImageEncoder imageEncoderForJpeg = new JpegEncoder()
{
Quality = 80,
};
IImageEncoder imageEncoderForPng = new PngEncoder()
{
CompressionLevel = PngCompressionLevel.Level9,
};
_fileRepo = new FileRepo
{
FileName = fileName,
FileExtension = fileExtension,
FileType = file.ContentType,
CreatedDate = DateTime.Now
};
using (var ms = new MemoryStream())
{
if (fileExtension == ".png")
{
image.Save(ms, imageEncoderForPng);
}
if (fileExtension == ".JPEG" || fileExtension == ".jpg")
{
image.Save(ms, imageEncoderForJpeg);
}
await file.CopyToAsync(ms);
_fileRepo.FileData = ms.ToArray();
}
}
return _fileRepo;
}
i dont know whats wrong with that method , it should be less size then first one right ?
let me know if that question is duplicate.

XF skiasharp downloads corrupted PDF

I want to create PDF reports using Xamarin Forms. I have tried creating sample PDF usin skiasharp plugin. But I am facing strange problem.
PDF can be opened in Mobile Device(Android 10.0, API 29) very easily. but if I try to open same PDF in laptop then it shows error message saying Can not open corrupted PDF.
Also if we look at size of the PDF, It is 183 KB in device and 0KB in laptop.
Code
private void GenerateDocument()
{
try
{
var root = EnsureTempDataDirectory("CreatePdfSample");
path = Path.Combine(root, $"{Guid.NewGuid():N}.pdf");
if (!isSupported || (isSupported && File.Exists(path)))
return;
var metadata = new SKDocumentPdfMetadata
{
Author = "Cool Developer",
Creation = DateTime.Now,
Creator = "Cool Developer Library",
Keywords = "SkiaSharp, Sample, PDF, Developer, Library",
Modified = DateTime.Now,
Producer = "SkiaSharp",
Subject = "SkiaSharp Sample PDF",
Title = "Sample PDF",
};
var stream = SKFileWStream.OpenStream(path);
var document = SKDocument.CreatePdf(path, metadata);
if (document == null)
{
isSupported = false;
return;
}
var paint = new SKPaint
{
TextSize = 64.0f,
IsAntialias = true,
Color = 0xFF9CAFB7,
IsStroke = true,
StrokeWidth = 3,
TextAlign = SKTextAlign.Center
};
var pageWidth = 840;
var pageHeight = 1188;
// draw page 1
using (var pdfCanvas = document.BeginPage(pageWidth, pageHeight))
{
// draw button
var nextPagePaint = new SKPaint
{
IsAntialias = true,
TextSize = 16,
Color = SKColors.OrangeRed
};
var nextText = "Next Page >>";
var btn = new SKRect(pageWidth - nextPagePaint.MeasureText(nextText) - 24, 0, pageWidth, nextPagePaint.TextSize + 24);
pdfCanvas.DrawText(nextText, btn.Left + 12, btn.Bottom - 12, nextPagePaint);
// make button link
pdfCanvas.DrawLinkDestinationAnnotation(btn, "next-page");
// draw contents
pdfCanvas.DrawText("...PDF 1/2...", pageWidth / 2, pageHeight / 4, paint);
document.EndPage();
}
// draw page 2
using (var pdfCanvas = document.BeginPage(pageWidth, pageHeight))
{
// draw link destintion
pdfCanvas.DrawNamedDestinationAnnotation(SKPoint.Empty, "next-page");
// draw contents
pdfCanvas.DrawText("...PDF 2/2...", pageWidth / 2, pageHeight / 4, paint);
document.EndPage();
}
// end the doc
document.Close();
}
catch (Exception ex)
{
throw;
}
}
For sample, I have taken reference from Skiasharp Sample available on github.
Any help would be appreciated
Edit
As I have Created folder named CreatePDFSample, path of the file is
/Internal Storage/Download/CreatePdfSample/8c134318ca8d49f59d7a57e244845107.pdf
One more thing I noted right now, One of the 10-12 files I have created is opening in laptop as well. It is also at the same path. I can't understand what might be issue here.
Thanks
I had not disposed of the stream correctly. The using keyword for stream solved the issue.

Instagram & Processing - Real time view

I'm working on a small app similar to instaprint and need some help. I'm using the source code from Globalgram by Andrew Haskin, it searches instagram for a particular hashtag and displays the most recent image posted with that hashtag. The problem is it only does it once, I need it to continuously search for the hashtag and display an image when a new one is added, so a refresh, I've been tinkering with it but to no avail. Any help would be greatly appreciated
Code Below :
import com.francisli.processing.http.*;
PFont InstagramFont;
PImage backgroundimg;
PImage brand;
PImage userphoto;
PImage profilepicture;
String username;
String tag;
String[] tagStrings;
com.francisli.processing.http.HttpClient client;
void setup() {
size(580, 900);
smooth();
backgroundimg = loadImage("iso_background.jpg");
brand = loadImage("iso.jpg");
InstagramFont = loadFont("Helvetica-Bold-36.vlw");
client = new com.francisli.processing.http.HttpClient(this, "api.instagram.com");
client.useSSL = true;
//// instantiate a new HashMap
HashMap params = new HashMap();
//// put key/value pairs that you want to send in the request
params.put("access_token", "------ACCESS TOKEN HERE------");
params.put("count", "1");
client.GET("/v1/tags/coffee/media/recent.json", params);
}
void responseReceived(com.francisli.processing.http.HttpRequest request, com.francisli.processing.http.HttpResponse response) {
println(response.getContentAsString());
//// we get the server response as a JSON object
com.francisli.processing.http.JSONObject content = response.getContentAsJSONObject();
//// get the "data" value, which is an array
com.francisli.processing.http.JSONObject data = content.get("data");
//// get the first element in the array
com.francisli.processing.http.JSONObject first = data.get(0);
//// the "user" value is another dictionary, from which we can get the "full_name" string value
println(first.get("user").get("full_name").stringValue());
//// the "caption" value is another dictionary, from which we can get the "text" string value
//println(first.get("caption").get("text").stringValue());
//// get profile picture
println(first.get("user").get("profile_picture").stringValue());
//// the "images" value is another dictionary, from which we can get different image URL data
println(first.get("images").get("standard_resolution").get("url").stringValue());
com.francisli.processing.http.JSONObject tags = first.get("tags");
tagStrings = new String[tags.size()];
for (int i = 0; i < tags.size(); i++) {
tagStrings[i] = tags.get(i).stringValue();
}
username = first.get("user").get("full_name").stringValue();
String profilepicture_url = first.get("user").get("profile_picture").stringValue();
profilepicture = loadImage(profilepicture_url, "png");
String userphoto_url = first.get("images").get("standard_resolution").get("url").stringValue();
userphoto = loadImage(userphoto_url, "png");
//noLoop();
}
void draw() {
background(255);
imageMode(CENTER);
image(brand, 100, height/1.05);
if (profilepicture != null) {
image(profilepicture, 60, 70, 90, 90);
}
imageMode(CENTER);
if (userphoto != null) {
image(userphoto, width/2, height/2.25, 550, 550);
}
textFont(InstagramFont, 20);
if (username != null) {
text(username, 110, 115);
fill(0);
}
textFont(InstagramFont, 15);
if ((tagStrings != null) && (tagStrings.length > 0)) {
String line = tagStrings[0];
for (int i = 1; i < tagStrings.length; i++) {
line += ", " + tagStrings[i];
}
text(line, 25, 720, 550, 50);
fill(0);
}
}
AFAIK it should be the
client.GET("/v1/tags/coffee/media/recent.json", params);
line that actually polls Instagram. Try wrapping that in a function like this:
void getGrams() {
client.GET("/v1/tags/coffee/media/recent.json", params);
}
then call that once in setup() and then again when you want to ...
I'd start with trying to do it on mousePressed() or keyPressed(), so that it only fires once when you really want it to
Don't try to do it in draw() without a timer (something like if(frameCount % 5000 == 0) which will fire every five seconds ((which may be too fast still but you get the idea))

How to create a single-color Bitmap to display a given hue?

I have a requirement to create an image based on a certain color. The color will vary and so will the size of the output image. I want to create the Bitmap and save it to the app's temporary folder. How do I do this?
My initial requirement came from a list of colors, and providing a sample of the color in the UI. If the size of the image is variable then I can create them for certain scenarios like result suggestions in the search pane.
This isn't easy. But it's all wrapped in this single method for you to use. I hope it helps. ANyway, here's the code to create a Bitmap based on a given color & size:
private async System.Threading.Tasks.Task<Windows.Storage.StorageFile> CreateThumb(Windows.UI.Color color, Windows.Foundation.Size size)
{
// create colored bitmap
var _Bitmap = new Windows.UI.Xaml.Media.Imaging.WriteableBitmap((int)size.Width, (int)size.Height);
byte[] _Pixels = new byte[4 * _Bitmap.PixelWidth * _Bitmap.PixelHeight];
for (int i = 0; i < _Pixels.Length; i += 4)
{
_Pixels[i + 0] = color.B;
_Pixels[i + 1] = color.G;
_Pixels[i + 2] = color.R;
_Pixels[i + 3] = color.A;
}
// update bitmap data
// using System.Runtime.InteropServices.WindowsRuntime;
using (var _Stream = _Bitmap.PixelBuffer.AsStream())
{
_Stream.Seek(0, SeekOrigin.Begin);
_Stream.Write(_Pixels, 0, _Pixels.Length);
_Bitmap.Invalidate();
}
// determine destination
var _Folder = Windows.Storage.ApplicationData.Current.TemporaryFolder;
var _Name = color.ToString().TrimStart('#') + ".png";
// use existing if already
Windows.Storage.StorageFile _File;
try { return await _Folder.GetFileAsync(_Name); }
catch { /* do nothing; not found */ }
_File = await _Folder.CreateFileAsync(_Name, Windows.Storage.CreationCollisionOption.ReplaceExisting);
// extract stream to write
// using System.Runtime.InteropServices.WindowsRuntime;
using (var _Stream = _Bitmap.PixelBuffer.AsStream())
{
_Pixels = new byte[(uint)_Stream.Length];
await _Stream.ReadAsync(_Pixels, 0, _Pixels.Length);
}
// write file
using (var _WriteStream = await _File.OpenAsync(Windows.Storage.FileAccessMode.ReadWrite))
{
var _Encoder = await Windows.Graphics.Imaging.BitmapEncoder
.CreateAsync(Windows.Graphics.Imaging.BitmapEncoder.PngEncoderId, _WriteStream);
_Encoder.SetPixelData(Windows.Graphics.Imaging.BitmapPixelFormat.Bgra8,
Windows.Graphics.Imaging.BitmapAlphaMode.Premultiplied,
(uint)_Bitmap.PixelWidth, (uint)_Bitmap.PixelHeight, 96, 96, _Pixels);
await _Encoder.FlushAsync();
using (var outputStream = _WriteStream.GetOutputStreamAt(0))
await outputStream.FlushAsync();
}
return _File;
}
Best of luck!

Rally SOAP API - How do I add an attachment to a Hierarchical Requirement?

I have followed this code to add attachment to a HierarchicalRequirement.
I get the following error:
validation error: Attachment.attachments[0] should not be null
How do I add an attachment to a Hierarchical Requirement?
Can you post a code excerpt that illustrates the problem? If you followed the approach in Rally SOAP API - How do I add an attachment to a TestCaseResult you're on the right track. Following is a quick code sample that works for me when adding an attachment to a story:
// issue query for target story
QueryResult queryResult = service.query(workspace, objectType, queryString, orderString, fetchFullObjects, start, pageSize);
// look at the object returned from query()
Console.WriteLine("Query returned " + queryResult.TotalResultCount + " objects");
// Grab the resulting story
DomainObject rallyObject = queryResult.Results.First();
HierarchicalRequirement queryStory = (HierarchicalRequirement)rallyObject;
// Read In Image Content
String imageFilePath = "C:\\Users\\username\\";
String imageFileName = "image1.png";
String fullImageFile = imageFilePath + imageFileName;
var imageFileLength = new FileInfo(fullImageFile).Length;
Image myImage = Image.FromFile(fullImageFile);
Console.WriteLine("Image File Length: " + imageFileLength);
// Convert Image to Byte Array format
byte[] imageByteArray = ImageToByteArray(myImage, System.Drawing.Imaging.ImageFormat.Png);
var imageNumberBytes = imageByteArray.Length;
// Create the Attachment Content
AttachmentContent attachmentContent = new AttachmentContent();
attachmentContent.Content = imageByteArray;
attachmentContent.Workspace = workspace;
CreateResult result = service.create(attachmentContent);
attachmentContent = (AttachmentContent)result.Object;
// Create the Attachment Container, wire it up to the AttachmentContent
Attachment myAttachment = new Attachment();
myAttachment.ContentType = "image/png";
myAttachment.Content = attachmentContent;
myAttachment.Name = "image1.png";
myAttachment.Size = imageNumberBytes ;
myAttachment.SizeSpecified = true;
myAttachment.User = user;
myAttachment.Artifact = queryStory;
myAttachment.Workspace = workspace;
// Create the attachment in Rally
result = service.create(myAttachment);
Console.WriteLine(result.Object);
}
public static byte[] ImageToByteArray (Image image, System.Drawing.Imaging.ImageFormat format)
{
using (MemoryStream ms = new MemoryStream())
{
// Convert Image to byte[]
image.Save(ms, format);
byte[] imageBytes = ms.ToArray();
return imageBytes;
}
}
}