mardi 31 mars 2015

Add image and value to a panel?

I was able to add image to my panel with the following code, but now my problem is i need to retrieve some information from the image etc(key value)


Is that possible to add in a value to every image ?so I can get it when I need



foreach (System.Drawing.Image img in imagelist)
{
PictureBox imagePicBox = new PictureBox();
imagePicBox.Name = "image" + imagePanel.Controls.Count.ToString();


imagePicBox.Image = img;




imagePicBox.Size = imagePicBox.Image.Size;
imagePicBox.BackColor = Color.Black;
imagePicBox.SizeMode = PictureBoxSizeMode.StretchImage;
imagePicBox.BorderStyle = BorderStyle.FixedSingle;


imagePanel.Controls.Add(imagePicBox);



}

Picasso: Get image width and size after fit() method



In my listview, each item has an ImageView laid on a 9-patch shadow background:


there are redundant padding


The problem is the image cannot fit the background because I used Picasso with fit() and centerCrop() from this (code below).



Picasso.with(getActivity())
.load(imageUrl)
.placeholder(R.drawable.placeholder)
.error(R.drawable.error)
.fit().centerCrop()
.into(imageView);


layout view:



<ImageView
android:id="@+id/thumbnail"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="@drawable/feed_image_shadow"
android:contentDescription="@string/app_name"
android:minHeight="180dp" />


As far as I know, fit() with calculate ImageView's dimension but showdow by 9 patch change the actual image area a little bit. Now I think I have to find image view's dimension after fit() method then change width smaller alittle bit. Do you know how to achieve that or is there any other solution?

Thank you so much


HTML/CSS - Positioning tag from the right side of container, and to the right of another tag

I have a web page that has a div container with 3 images. Image 1 fills up the height of the container on the left side. Image 2 is centered in the container, but to the right of Image 1. Image 3 is in the bottom right corner of the container. I would like Image 3 to always be to the right of Image 1. Is there a way to achieve this using html/css? Currently if I resize the window, Image 3 covers up (or is covered by) Image 1 (depending on the z-index).


Sample Illustration:



- - - - - - - -
| | |
| | |
| | - - | |
| | - - | |
| | | - - |
| | | - - |
- - - - - - - -


Sample Code:



<div background="{some background}" style="width: 100%; height: 750px; position: relative; background: {some background};">
<img src="{some image 1}" style="position: absolute; width: auto; height: 100%; left: 0px; z-index: 1;">
<img src="{some image 2}" style="position: absolute; width: 456px; height: auto; margin: auto; top: 0; left: 432px; bottom: 0; z-index: 2;">
<img src="{some image 3}" style="position: absolute; width: 456px; height: auto; margin: auto; bottom: 25px; right: 25px; z-index: 2;">
</div>

Accessing a png from inside a JAR

Currently I have a compiled JAR file as follows



RunMe.jar
-GUIFile.class
-Main.class
-Notify.class
-resources
--sprites
---myimg.png
-com
--random
---package
----MakeNotify.class


Please explain to me how to access the PNG myimg.png inside MakeNotify.java


Thanks for all the advice in advanced


How to make website (images/ tables) resize proportionnally to fit screen size [on hold]

My friend has a html website with many pages containing various text or pictures. She received a google warning that the site can't be seen on ipads/smartphones and would like that all the site rescale proportionally so it can be seen on ipads at least.


The problem is all the design is html based, so you can have in on line 1 to 3 images of different sizes, without any use of css. All design is html based.


Changing each image/table one by one would be few weeks of boring work as this site has many pages (hundreds, about animals/plants)


I have seen most topic describing this css solution: img {width: 100%; height: auto;width: auto\9; /* ie8 */}


However this does not work in this case because there is various numbers of images beside each others.


Is there an easy way to resize all the site proportionnally?


CSS, or Javascript, or Jquery ?


Many thanks


matplotlib show many images in single pdf page

The following python script is given an image as input and shows it 8 times in a single pdf page:



pdf = PdfPages( './test.pdf' )
gs = gridspec.GridSpec(2, 4)

ax1 = plt.subplot(gs[0])
ax1.imshow( _img )

ax2 = plt.subplot(gs[1])
ax2.imshow( _img )

ax3 = plt.subplot(gs[2])
ax3.imshow( _img )

# so on so forth...

ax8 = plt.subplot(gs[7])
ax8.imshow( _img )

pdf.savefig()
pdf.close()


The input image can have different size (unknown a priori). I tried using the function gs.update(wspace=xxx, hspace=xxx) to change the spacing between the images, hoping that matplotlib would automagically resize and redistribute the images to have least white space possible. However, as you can see below, it didn't work as I expected.



Is there a better way to go to achieve the following?




  1. Have images saved with max resolution possible

  2. Have less white space possible


Ideally I would like the 8 images to completely will the page size of the pdf (with minimum amount of margin needed).


enter image description here


enter image description here


Is there a Grunt Task to Add a Background Image to All Images in Folder?

Background


I have a large number of employee images for a website. Each one is a headshot, and the area around the head is transparent:


enter image description here


On the website, I apply a background-image to each img.



<img class="employee" src="employee_x.jpg" />

.employee {
background:url('employee_background.jpg') center center / cover;
}


It ends up looking like:


enter image description here


This lets me easily change out the images in the future, for all of them. Problem is, the background downloads first and the site owner is complaining that it looks fake when the background loads first.




Problem


I now need to combine all of them and resave the images, with the backgrounds and employee images saved together. I can do this with Photoshop or Paint.net, but it takes a lot of time to go through every single image.




Goal


I want it to take a folder with employee_background.jpg and all the other employee photos and then resave all of them into a production folder, using the background.



employees/john_smith.png
employees/sally_norton.png
employees/bill_miller.png
employees/employee_background.jpg

---->

employees/production/john_smith.png
employees/production/sally_norton.png
employees/production/bill_miller.png
employees/production/employee_background.jpg


Is there a Grunt task that can do this for me?


Trying to hide image styling, if no image is present - Advanced Custom Fields images

I have styled my images on my Content Page Template to have borders, backgrounds and box-shadow. If I don't use the optional image field and leave it empty, it leaves the css styling with a small box. I have been trying to hide the entire .content-img class if there is no image present. The code below works fine for rendering the images if they are present. How to hide it if no image is present.


<?php the_field('top_headline'); ?></h1>

<div class="content-top"><?php the_field('content_top'); ?></div> <div class="content-img"><?php $image = get_field('content_image'); $size = 'medium'; // (thumbnail, medium, large, full or custom size) if( $image ) { echo wp_get_attachment_image( $image, $size ); } ?>


Thanks for your help in advance.


Upload Picture in Android to Server

I've been on this subject for weeks and I can't seem to find the answer I'm looking for. I've just started out learning this and I was hoping I could find some great resources to aid in my study. I've found some amazing references at GitHub, but only to find that I'm encountering problems every time I try and debug my app.


What I'm trying to achieve:



  1. To set up a picture upload page (for user's profile picture);

  2. Link the page to the server to store the uploaded pictures; And also try to implement this code by AB1209 to get a fix from loading from Photos app (instead of Gallery) on higher API androids;

  3. Find out a way to link the file path to the user's info at database. I.e. The User's profile picture. (I don't want to store it in BLOB)


I'm currently trying this code from GitHub: webile-android and so far it's very easy for me to understand what's on the code. However when I tried debugging the app (clicked on the image to upload), my app has stopped working at that point and I got the following error.


Any help would truly be appreciated!



04-01 10:06:35.801 1632-1632/worka.biz.worka E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: worka.biz.worka, PID: 1632
java.lang.IllegalStateException: Could not execute method of the activity
at android.view.View$1.onClick(View.java:4007)
at android.view.View.performClick(View.java:4756)
at android.view.View$PerformClick.run(View.java:19749)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5221)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)
Caused by: java.lang.reflect.InvocationTargetException
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at android.view.View$1.onClick(View.java:4002)
at android.view.View.performClick(View.java:4756)
at android.view.View$PerformClick.run(View.java:19749)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5221)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)
Caused by: java.lang.NoClassDefFoundError: Failed resolution of: Lorg/apache/http/entity/ContentType;
at org.apache.http.entity.mime.content.ByteArrayBody.<init>(ByteArrayBody.java:67)
at org.apache.http.entity.mime.content.ByteArrayBody.<init>(ByteArrayBody.java:87)
at worka.biz.worka.ManagePictureActivity.executeMultipartPost(ManagePictureActivity.java:111)
at worka.biz.worka.ManagePictureActivity.uploadPhoto(ManagePictureActivity.java:85)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at android.view.View$1.onClick(View.java:4002)
at android.view.View.performClick(View.java:4756)
at android.view.View$PerformClick.run(View.java:19749)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5221)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)
Caused by: java.lang.ClassNotFoundException: Didn't find class "org.apache.http.entity.ContentType" on path: DexPathList[[zip file "/data/app/worka.biz.worka-1/base.apk"],nativeLibraryDirectories=[/vendor/lib, /system/lib]]
at dalvik.system.BaseDexClassLoader.findClass(BaseDexClassLoader.java:56)
at java.lang.ClassLoader.loadClass(ClassLoader.java:511)
at java.lang.ClassLoader.loadClass(ClassLoader.java:469)
at org.apache.http.entity.mime.content.ByteArrayBody.<init>(ByteArrayBody.java:67)
at org.apache.http.entity.mime.content.ByteArrayBody.<init>(ByteArrayBody.java:87)
at worka.biz.worka.ManagePictureActivity.executeMultipartPost(ManagePictureActivity.java:111)
at worka.biz.worka.ManagePictureActivity.uploadPhoto(ManagePictureActivity.java:85)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at android.view.View$1.onClick(View.java:4002)
at android.view.View.performClick(View.java:4756)
at android.view.View$PerformClick.run(View.java:19749)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5221)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)
Suppressed: java.lang.ClassNotFoundException: org.apache.http.entity.ContentType
at java.lang.Class.classForName(Native Method)
at java.lang.BootClassLoader.findClass(ClassLoader.java:781)
at java.lang.BootClassLoader.loadClass(ClassLoader.java:841)
at java.lang.ClassLoader.loadClass(ClassLoader.java:504)
... 18 more
Caused by: java.lang.NoClassDefFoundError: Class not found using the boot class loader; no stack available


This is the JAVA code handling the uploading function:



public class ManagePictureActivity extends Activity {

private static final String TAG = ManagePictureActivity.class.getSimpleName();

private static final int SELECT_PICTURE = 100;

private ImageView previewImage;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_manage_picture);

previewImage = (ImageView) findViewById(R.id.previewImage);
}

public void pickPhoto(View view) {
//TODO: launch the photo picker
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent,
"Select Picture"), SELECT_PICTURE);
}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(resultCode == RESULT_OK) {
Bitmap bitmap = getPath(data.getData());
previewImage.setImageBitmap(bitmap);
}
}

private Bitmap getPath(Uri uri) {

String[] projection = { MediaStore.Images.Media.DATA };
Cursor cursor = managedQuery(uri, projection, null, null, null);
int column_index = cursor
.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
String filePath = cursor.getString(column_index);
cursor.close();
// Convert file path into bitmap image using below line.
Bitmap bitmap = BitmapFactory.decodeFile(filePath);

return bitmap;
}

public void uploadPhoto(View view) {
try {
executeMultipartPost();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

public void executeMultipartPost() throws Exception {

try {

ByteArrayOutputStream bos = new ByteArrayOutputStream();

BitmapDrawable drawable = (BitmapDrawable) previewImage.getDrawable();

Bitmap bitmap = drawable.getBitmap();

bitmap.compress(CompressFormat.JPEG, 50, bos);

byte[] data = bos.toByteArray();

HttpClient httpClient = new DefaultHttpClient();

HttpPost postRequest = new HttpPost(AppConfig.FILE_UPLOAD_URL);

String fileName = String.format("File_%d.png",new Date().getTime());
ByteArrayBody bab = new ByteArrayBody(data, fileName);

// File file= new File("/mnt/sdcard/forest.png");

// FileBody bin = new FileBody(file);

MultipartEntity reqEntity = new MultipartEntity(

HttpMultipartMode.BROWSER_COMPATIBLE);

reqEntity.addPart("file", bab);

postRequest.setEntity(reqEntity);
int timeoutConnection = 60000;
HttpParams httpParameters = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpParameters,
timeoutConnection);
int timeoutSocket = 60000;
HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);
HttpConnectionParams.setTcpNoDelay(httpParameters, true);

HttpResponse response = httpClient.execute(postRequest);

BufferedReader reader = new BufferedReader(new InputStreamReader(

response.getEntity().getContent(), "UTF-8"));

String sResponse;

StringBuilder s = new StringBuilder();

while ((sResponse = reader.readLine()) != null) {

s = s.append(sResponse);

}

System.out.println("Response: " + s);

} catch (Exception e) {

// handle exception here
e.printStackTrace();

// Log.e(e.getClass().getName(), e.getMessage());

}

}}


And also the XML code:



<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://ift.tt/nIICcg"
xmlns:tools="http://ift.tt/LrGmb4"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:baselineAligned="false"
android:orientation="vertical" >

<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:gravity="center"
android:orientation="vertical" >

<ImageView
android:id="@+id/previewImage"
android:layout_width="wrap_content"
android:layout_height="0dp"
android:layout_weight="0.5" />

<Button
android:onClick="pickPhoto"
android:layout_height="@dimen/login_height"
android:layout_width="@dimen/login_width"
android:layout_gravity="center"
android:layout_marginTop="30dp"
android:background="#80f1ce25"
android:textAllCaps="false"
android:textColor="#ffffff"
android:textSize="25sp"
android:textStyle="normal"
android:text="Select from gallery"/>

<Button
android:onClick="uploadPhoto"
android:layout_height="@dimen/login_height"
android:layout_width="@dimen/login_width"
android:layout_gravity="center"
android:layout_marginTop="30dp"
android:background="#80f1ce25"
android:textAllCaps="false"
android:textColor="#ffffff"
android:textSize="25sp"
android:textStyle="normal"
android:text="Upload photo to server"/>

</LinearLayout>

</RelativeLayout>


And my php file (directed from AppConfig.FILE_UPLOAD_URL) is as follows: This php file is from AndroidHive because the previous reference seems to have omitted this detail. So I thought this might work.



fileUpload.php
<?php

// Path to move uploaded files
$target_path = "uploads/";

// array for final json respone
$response = array();

// getting server ip address
$server_ip = gethostbyname(gethostname());

// final file url that is being uploaded
$file_upload_url = 'http://' . $server_ip . '/' . 'picture_upload_directory' . '/' . $target_path;

if (isset($_FILES['image']['name'])) {

$target_path = $target_path . basename($_FILES['image']['name']);

// reading other post parameters
$email = isset($_POST['email']) ? $_POST['email'] : '';
$website = isset($_POST['website']) ? $_POST['website'] : '';

$response['file_name'] = basename($_FILES['image']['name']);
$response['email'] = $email;
$response['website'] = $website;

try {
// Throws exception incase file is not being moved
if (!move_uploaded_file($_FILES['image']['tmp_name'], $target_path)) {
// make error flag true
$response['error'] = true;
$response['message'] = 'Could not move the file!';
}

// File successfully uploaded
$response['message'] = 'File uploaded successfully!';
$response['error'] = false;
$response['file_path'] = $file_upload_url . basename($_FILES['image']

['name']);
} catch (Exception $e) {
// Exception occurred. Make error flag true
$response['error'] = true;
$response['message'] = $e->getMessage();
}
} else {
// File parameter is missing
$response['error'] = true;
$response['message'] = 'Not received any file!';
}



// Echo final json response to client
echo json_encode($response);
?>

How to get tap position to add control?

I have a Windows phone 8.0 project that has an image. When the user taps on the image, I have to get the position of the tap and add a text box to this location (above image).


For now, I use the following code, but I always get a wrong position



MessageBox.Show("vao day");
var mp = GetMousePoint(e);
MessageBox.Show("x=" + mp.X + "_" + "y=" + mp.Y);
//x: 258; y:97
double top= 0; double right = 0; double bottom =0; double left=0;
top = e.GetPosition(OrginalImage).Y; //(double)mp.Y - 50;
left = e.GetPosition(OrginalImage).X; //(double)mp.X - 50;

MessageBox.Show("x=" + left.ToString() + "_" + "y=" + top.ToString());
//add textbox to this position
TextBox newtext = new TextBox();
newtext.Text = "truongpm";
newtext.Margin = new Thickness(left, top, right, bottom);
newtext.Width = 124;
newtext.Height = 68;

//button.VerticalAlignment = 234;
//Add contentpanel to your page if there's not one already.
ContentPanel.Children.Add(newtext);
newtext.Visibility = System.Windows.Visibility.Visible;


enter image description here


Can anybody help me please! Thanks


This is my xaml code



<Grid x:Name="ContentPanel" Margin="5">
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<Image Grid.Row="0" MouseMove="Image_MouseMove" Name="OrginalImage" Stretch="Fill" Height="250" Source="/Assets/vd1.png"/>
<Button Grid.Row="1" Content="ALter" Width="100" Height="80" Click="AlterButton_Click" Foreground="#FFD66A6A" BorderBrush="#FF16C71E" Margin="10,0,360,0"/>
<Button Grid.Row="1" Content="Save" Width="100" Height="80" Foreground="#FFD66A6A" BorderBrush="#FF16C71E" Margin="115,0,255,0" Click="Button_Click"></Button>
<Button Grid.Row="1" Content="Text" Width="100" Height="80" Foreground="#FFD66A6A" BorderBrush="#FF16C71E" Margin="115,0,055,0" Click="TextButton_Click"></Button>
<Image Grid.Row="2" Name="AlterImage" />

<!--<TextBox HorizontalAlignment="Left" Height="72" TextWrapping="Wrap" Text="TextBox" VerticalAlignment="Top" Width="180" Margin="110,65,0,0" Grid.Row="0"/>-->
</Grid>

</Grid>

jQuery: object is not a function

I've been trying to get this to toggle two .pngs on button click. When I run the code, console throws and error: Uncaught TypeError: object is not a function. Here is my code:



<body>
<h1>My Website</h1>

<div>
<button data-file="bs">BMW </button>
<button data-file ="ms">Mercedes</button>
</div>

<div id="bmw">
<img src="bmw.png">
</div>

<div id="mercedes">
<img src="merc.png">
</div>

<script src="http://ift.tt/13qgtmt"></script>

<script>

(function(){
var link = $('link');
$('button').click(function() {
var $this =$(this)
car = $(this).data('file');
console.log(car);
link.attr('href', car + '.png');
});
})();


Which object is this referring to? And how do I alter the code?


Thanks in advance!


Display a generated gif;base64 image using C# code behind in img using JavaScript

i have the following C# code behind (it is a code that generate dynamically an Bmp image and than convert it to gif and returns it to be displayed):



[WebMethod]
public static HtmlImage ProcessIT()
{
var bitmap = DrawingMethod(); //Method that draws dynamically Bmp Image
MemoryStream ms = new MemoryStream();
bitmap.Save(ms, ImageFormat.Jpeg);
var base64Data = Convert.ToBase64String(ms.ToArray());
HtmlImage img = new HtmlImage
{Src = "data:image/gif;base64," + base64Data, Width = 940};
return img; //The Gif image i want to display on the page
}


Than, I'm calling this C# behind code Method from : Generate_onclick() which is a JavaScript



function Generate_onclick()
{
PageMethods.ProcessIT(onSucess, onError);
function onSucess(result)
{
//Here is where i am not sure how it's done !!!!!!
document.getElementById("imgCtrl").src = result;
}

function onError(result)
{
alert('Something wrong.');
}
}


in here is the HTML Code :



<img src="" alt="" style="width: 100%;" runat="server" id="imgCtrl" />


is this the right way to display my image in the page ? if not than how ?


Displaying RGB numbers of an image

I need to display all of the RGB numbers for each pixel in a chosen picture, with each number separated by a space, and use println (break) after every row of the picture. I've figured out and written the code to return all of the RGB numbers, but I don't know how to break after each row. Here is my code so far..



public void getColor()
{
System.out.println("This picture's dimensions are: "+this.getWidth()+" by "+this.getHeight());
for (int row=0; row < this.getHeight(); row++) // gives the number of rows
{
for (int col=0; col < this.getWidth(); col++)// gives the number of columns
{
Pixel pix = this.getPixel(col,row);
System.out.print(pix.getRed()+" "+pix.getGreen()+" "+pix.getBlue()+" ");
} // end of inner loop
}// end of outer loop
} // end of method

Xcode Moving Image on A Curve + Spritesheets

Im working on a simple cups and ball game and right now I am making the cups move by using



_image.animationImages = [NSArray arrayWithObjects:...


and then having all of the images in the animation but each animation is about 200 images which is making it really big and slow, is there a way to have each cup move along a curve I set and just have the one image of the cup instead of the thousands for all the animations?


And also I plan to be able to have different cups to choose from, is there a way I can put all the cups in a sprite sheet instead of having each individual image? I do not want to use cocos2d because I am not familiar with it and do not want to restart this project.


Python 3, changing colour of an image

what is the easiest way to change the colour of the whole image with a RGB value? I have tried wand, however the documentation didn't make much sense to me, and I can only find changing the intensity of the colours in the Pillow documentation.


I tried multiple solutions online, however either they didn't do what I wanted, or were out of date and didn't work.


I want it so that the whole image gets tinted and I can control the tint by changing the RGB colour, bit like this:


http://ift.tt/1bH3FwT


I can implement the wheel myself, however the actual changing colour part is confusing me. Hopefully it will be an easy solution :)


Force image extension on right click save

I'm having some issues with images on my site which I'm downloading from an image delivery service.


They're displaying perfectly fine, but the issue comes if a user tries to right click and save the image. The images seem to be leaving off the image extension. Is there any way to force the image to download as, say a jpg? I've looked at the download attribute, but I think that's only valid on links, so it's not valid in this case.


How to pass a dropdown menu from HTML to external Javascript

My problem is I am making a virtual tour using pictures. I have a dropdown menu so when you click on one of the locations it flys you right to that spot. In my javascript file I have the each location in an array. so...



<div id = "menu">

<select id = 'flyto' onchange = 'putPicture(this)'>
<option value="Hyde">Hyde</option>
<option value="Lamson">Lamson</option>
<option value="Smith">Smith</option>
<option value="Sodexo">Sodexo</option>
</select>

</div


this is my html I have the external javascript including at the top so thats not a problem my problem is in tour.js I have



function putPicture(locaValue)
{
var select = document.getElementById('flyto');
var location = select.options[select.selectedIndex].value;
var pano = $('#pano').leanorama(tour.location);
pano.on('leanoramaHotspotClick', function(e, hotspot) {
if (hotspot.type == 'nav') $(this).trigger('leanoramaRefresh',
tour[hotspot.value]);
});
}


but up above in my javascript I have each location in an array called tour where each value is the name of the location (Hyde, Lamson, Smith, Sodexo). Is it possible to have the same values in my HTML as in my JS? The pictures wont load and when i switch to a different value in the menu I get an error because I think its taking in only the value from the HTML menu instead of converting it to my Pictures value. Im using leanorama from github that using cubic pictures( so 6 sides to make a panorama)


Decrease loading time large query with images

I have a table on my website which gives the visitor an overview of many football players including their photo, club and nation image. It loads these players from a database which has 14000 of them and shows only 30 players per page. Now the problem is, it takes too long to load these players and their 3 images. I already tried Lazyloader which took away some of the loading time but not enough.


Do you have any tips how I can decrease the loading time of my page?


Edit* Link to page loading stats: http://ift.tt/1DlnX9K


It seems that the request loading time causes 76% (over 1 sec.) of the loading time. How do I decrease this?


automatic picture size Java

everyone, I'm doing a project of Snakes and Ladders, I have everything ready only with console for now but I have to implement a graphics interface.


My program generates a 10 by 10 matrix and is filled with snakes and ladders randomly. Five of each. It's all fine when you're doing it in console because you just need to print the beginning and the end with text.


Now my problem is that I want to create a JFrame with the 100 squares(I plan to do this with images, one for each square and organize it inside a panel with gridlayout), and as the snakes and ladders are randomly created I want to know if there's a way to, for example, knowing that my snakes begins in square 60 and ends in square 32, to automate that my snake appears in that space?


I guess I have to create the images of different lenghts of snakes and ladders, but how to I make them fit in the space I need them? Thank you.


Edit If you need the source code, please tell me.


Drawing a boundary around some dots in an image

I have recently started working on opencv. I have an image having several dots in a line. I want to make a rectangular border around these dots. I have applied some basic C algorithm but it didn't work for me. This is my code.



int main()

{

cv::Mat image = imread("C:/Users/Ravi Sharma/Desktop/img.bmp");

for(int i =0; i < image.rows; i++){
for(int k = 0; k <image.cols; k ++){
if((image.at<cv::Vec3b>(k,i)[0] == 0)&&(image.at<cv::Vec3b>(k,i)[1] == 135)&&(image.at<cv::Vec3b>(k,i)[2] == 255))
{
(image.at<cv::Vec3b>(k,i)[0] = 0)&&(image.at<cv::Vec3b>(k,i)[1] = 0)&&(image.at<cv::Vec3b>(k,i)[2] = 255);
}
}

}
imwrite("C:/Users/Ravi Sharma/Desktop/img1.bmp",image);
cv::namedWindow("Window1");
cv::imshow("Window1",image);
cv::waitKey(50000);
return 1;
}


This code is not updating the pixel value. Please help me correcting the code to get the desired result. How I can use cvminmaxloc function to do the same. Thanx in advance.


Pictures sliding up or down by mouse hover

Please see sites like


http://ift.tt/1aeKxWt


http://ift.tt/1aeKxWv


Inside the slider if you hover the mouse up or down the image inside the slider moves up or down.


Is it achieved through angular.js or node.js or javascript/jquery itself ?


Thanks


Reduce number of levels per pixel, creating a mirror image, C++

I have a greyscale image that has a resolution of 150 x 200 pixels.


Task:


Create a function to count the number of black pixels in the image and display this.


Create a function that will invert the image.


Create a function that will reduce the number of levels per pixel , that is - setting the lower 6 bits in each pixel to 0 using the bitwise AND operator. The function should reduce the number of levels used per pixel to four.


Create a function that will create a mirror image, that is - so that for every row, pixel value in element 0 should be swapped with pixel value in element 149, and element 1 with element 148 etc...


So far, I have completed the first two parts of the task, however I am struggling with creating correct working functions for the last two (shown by asterisk characters) , any ideas?


My code:



#include <QCoreApplication>
#include <iostream>
#include "ImageHandle.h"

using namespace std;


int CountBlackPixels (unsigned char PixelGrid[WIDTH][HEIGHT]);


void InvertImage (unsigned char PixelGrid[WIDTH][HEIGHT]);


void ReducePixelLevel (unsigned char PixelGrid[WIDTH][HEIGHT]);


void MirrorImage (unsigned char PixelGrid[WIDTH][HEIGHT]);


int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);

unsigned char PixelGrid[WIDTH][HEIGHT]; // Image loaded from file


// If the file "Parrot.png" cannot be loaded ...
if (!loadImage(PixelGrid, "Parrot.png"))
{
// Display an error message
cout << "Error loading file \"Parrot.png\"" << endl;
}
else
{
cout << "File \"Parrot.png\" opened successfully" << endl;

// Demo of use of saveImage - to create a copy as "ParrotCopy.png"
// This should be modified to save the new images as specified
if (saveImage(PixelGrid, "ParrotCopy.png"))
{
cout << "File \"ParrotCopy.png\" saved successfully" << endl;
}
else
{
cout << "Could not save \"ParrotCopy.png\"" << endl;
}
}

// Display number of black pixels ...
cout << "\nNumber of black pixels : " << CountBlackPixels(PixelGrid) << endl;

InvertImage(PixelGrid);

{
if (saveImage(PixelGrid, "ParrotInv.png"))
{
cout << "\nFile \"ParrotInv.png\" saved successfully" << endl;
}
else
{
cout << "\nCould not save \"ParrotInv.png\"" << endl;
}

}

ReducePixelLevel(PixelGrid);

{
if (saveImage(PixelGrid, "Parrot4level.png"))
{
cout << "\nFile \"Parrot4level.png\" saved successfully" << endl;
}
else
{
cout << "\nCould not save \"Parrot4level.png\"" << endl;
}

}

MirrorImage (PixelGrid);

{
if (saveImage(PixelGrid, "ParrotMirror.png"))
{
cout << "\nFile \"ParrotMirror.png\" saved successfully" << endl;
}
else
{
cout << "\nCould not save \"ParrotMirror.png\"" << endl;
}

}
return a.exec();
}


int CountBlackPixels(unsigned char PixelGrid[WIDTH][HEIGHT])
{
int row;
int col;
int count = 0;

for (row = 0; row < WIDTH; row++)
{
for (col = 0; col < HEIGHT; col++)
{
if (PixelGrid[row][col] == 0)
count++;
}
}
return count;
}


void InvertImage (unsigned char PixelGrid[WIDTH][HEIGHT])
{
int row;
int col;

for (row = 0; row < WIDTH; row++)
{
for (col = 0; col < HEIGHT; col++)
{
PixelGrid[row][col] = ~PixelGrid[row][col];
}
}
}


void ReducePixelLevel (unsigned char PixelGrid[WIDTH][HEIGHT])


{
int row;
int col;

for (row = 0; row < WIDTH; row++)
{
for (col = 0; col < HEIGHT; col++)
{
*************************
}
}
}


void MirrorImage (unsigned char PixelGrid[WIDTH][HEIGHT])


{
***************************
}

how does a computer convert an image to binary?

how does a computer convert a colored or a black and white image to binary? conversely,how is the binary data converted to an image ? I mean to ask how does it actually process image data ?


How do I change the opacity of an image when I hover of my text?

Hey I'm new here and I really need some help! I have my own website, please don't judge I am new to HTML and CSS.. The problem is that I don't know how to change the opacity when I hover over my text.. I want it to become lighter if I'm hovering over my text in the menu on the right. Does anyone know how I can do this? Right now It's only changing when I hover over the image itself, the text changes too, but I want it to both change at the same time and on the same object, so I hover over the text; text changes and images opacity changes. Please help me out! Luca


http://ift.tt/1aelVNP


How to use AnnotationBbox with timestamps

I have produced a plot with timestamps. Now I want to upload an image to that graph by using following code.



fn = get_sample_data("path of image", asfileobj=False)
arr_lena = read_png(fn)
imagebox = OffsetImage(arr_lena, zoom=0.5)
ab = AnnotationBbox(imagebox,xy=(0,0),xybox=None,xycoords='data',boxcoords=None, box_alignment=(0,0))
ax.add_artist(ab)
plt.draw()
plt.show()


Now it is stating an error as dt = datetime.datetime.fromordinal(ix) ValueError: ordinal must be >= 1


I think this is because my x-axis ticks are dates. How to deal with this problem.


Images - Radiobuttons

I want to use images as radiobuttons. Everything is ok in Chrome and Firefox. But in IE it doesn't work... Test URL: http://ift.tt/1ND2rAu


CSS and HTML:



label > input{ /* HIDE RADIO */
display:none;

}
label > input + img{ /* IMAGE STYLES */
cursor:pointer;
border:2px solid transparent;

}

<label>
<input type="radio" name="shape" value="round" checked />
<img id="roundShape" src="css/images/round.jpg">
</label>

Android layouts - images for the different screen resolutions and the same density

I want to show some images on the background that is also image. Say my background image contains an empty squares, and I want to show an apple image that must appear exactly in one of that squares. I have a problems with the apple sizes, as the background scales and fits the screen, but apple image stays the same for the different resolution and the same density devices.


Say I have two ldpi devices with 240x320 and 480x800 resolutions. When I keep my drawable aple file in the drawable-ldpi folder, and use wrap_content for height and width (or fixed dp values) those 2 devices draw the apple with the same size, like it is described in the documentation.


The LinearLayout works slow when I stack them. Using RelaytiveLayout I must programmatically resize the images which is also "not so good" solution I guess.


I've found a solution here http://ift.tt/1NpJWzr that maps the dp-s.


They set dimen-s for values-sw300dp to be



<dimen name="_10sdp">10.00dp</dimen>


and for values-sw480dp to be



<dimen name="_10sdp">16.00dp</dimen>


and so on for the different cases ...


So when I set the with of the apple to be _10sdp it means different dp-s for my 2 devices with the same density and solves my problem. Is it a good solution as it seems to be for me? Is there any other easy ways?


How to fit canvas to wrap image size

Hello I have this canvas and image in it but I need to make it so the canvas wraps the image linked to its size. Right now i have put a test image and put size to be fixed. I want when i put and image the canvas to wrap it 100% width 100% height of the image.



var canvas=document.getElementById("canvas");
var ctx=canvas.getContext("2d");
var cw=canvas.width;
var ch=canvas.height;

var boxWidth=100;
var boxHeight=100;
var boxRows=Math.ceil(865/boxHeight);
var boxCols=Math.ceil(1152/boxWidth);
var boxes=new Array(boxRows*boxCols);
for(var i=0;i<boxes.length;i++){boxes[i]=false;}

var img=new Image();
img.onload=start;
img.crossOrigin='anonymous';
img.src="http://ift.tt/1Hs5yKZ";
function start(){

ctx.drawImage(img,0,0);

var d=ctx.getImageData(0,0,cw,ch).data;

for(var i=0;i<d.length;i+=4){
if(d[i+3]>200){
var px=parseInt(i/4);
var pixelY=parseInt(px/cw);
var pixelX=px-pixelY*cw;
var boxX=parseInt(pixelX/boxWidth);
var boxY=parseInt(pixelY/boxHeight);
boxes[boxY*boxCols+boxX]=true;
}
}

ctx.globalAlpha=0.25;
ctx.fillStyle='red';

for(var i=0;i<boxes.length;i++){
var y=parseInt(i/boxCols);
var x=i-y*boxCols;
if(boxes[i]==true){
ctx.fillRect(x*boxWidth,y*boxHeight,boxWidth,boxHeight);
}
}

ctx.globalAlpha=1.00;
ctx.fillStyle='black';


}


http://ift.tt/1EYdqxS


Segmenting fruits

My task is, to write a code in Matlab which one segments the fruits you can see on the picture below. So i should make 3 pictures, one where you can only see the orange, one with only grapefruit, and one with only lemon. Of course everything else should be black except the segmented object. I tried many methods but none of them worked for me. I guess i'm a bit newbie at image processing, so every helping hand would be great. Thank you. http://ift.tt/19whDjR


Image not appearing on Heroku

Until this morning I had no problems. I was viewing all the images on Heroku normally. Now I've noticed that one of the images is not there anymore. Actually it is there but it's transparent.. Does anyone know why?


html:



<img src="<%= asset_path('_MG_0414.jpg') %>" />


config/application.rb:



config.serve_static_files = true

Converting the captured coordinates into yards

There is a div with a background image with the following style :



#cont {
position: relative;
background-image: url('./st.png');
background-repeat: no-repeat;
width: 541px;
height: 349px;
}


Its background image has height of 349px and a height of 541px. The image is a soccer field. The length of a soccer field is 115 yards and breadth being 75 yards.


To convert the each captured coordinate (using mousemove event) into yards, I did this :



x_yard = (115*x1)/541
y_yard = (75*y1)/349

// x1 and y1 are the captured coordinates


It gives the incorrect result. XMax is near to 116 and YMax is near to 69. How could I convert the captured coordinates to yards?


Is it possible to make a torn paper effect on edges of a picture

Update 3


Hi guys, I updated the code (http://ift.tt/1NxJtcE) and now the edges look really like torn paper effect. It uses SVG by the way.


The Only problem is I don't know how to make the image as the background of the svg AT THE SAME TIME maintain the torn-paper-like edges.


Please have a look it. Any efforts are appreciated.




Update 2


It seems that it is impossible to achieve this effect without the help of PhotoShop(PS), so I would like to add PS as a part of solution.


I am not a PS expert, but from a quick thought, I think there are a few steps I need to do:



  • Use PS to create a torn paper "shell", let's say it's shell.png It should only have color on its edges and the color should be white; the inner area is transparent, so that we can place the picture in it.

  • Place shell.png on top of the picture, let's say banner.jpg, which means set the z-index of the div which uses shell as its background image to 1.

  • Use another div to contain the banner.jpg and set the z-index below the shell div.


Questions for this approach:




  • Is it responsive?




  • If not, is it possible to make it responsive? As I have to make it work properly on mobile devices.






I remember that I saw a beautifully designed website, there is a picture in the background and the edges of this picture look like torn paper effect which is fantastic!


I searched the similar questions here but it turns out that the effects in the answers are primitive, which are very simple rugged black lines.


What I want:



  1. I want this picture to be as wide as the device screen which means responsive.

  2. The edges of this picture look like torn paper.

  3. I will place this picture as a banner after the Top Navigation bar but before the content.


It should look like the white area in this picture. But in my case, I will need to fill in my picture to replace the white area.


enter image description here


Here is my code: Notice: in this code, the css uses an image as the edge, BUT that is not want I want. I just want the edges be the picture itself.(Is this possible?) So it will look like this one(the one on the right side, you can see that there is no white rugged edges) enter image description here



<div class="row">
<div id="letter" class="col-lg-12 col-md-12 col-sm-12 col-xs-12">

</div>
</div>

#letter { /*torn paper border*/
height:450px;
position:relative;
top:0;
bottom:0;
left:0;
right:0;
background-image:url('img/background.jpg');
background-size:cover;
opacity:0.8;
border-style: solid;
border-width: 40px 40px 40px;
-moz-border-image: url('http://ift.tt/1EUNiEb') 80 80 80 repeat;
-webkit-border-image: url('http://ift.tt/1EUNiEb') 80 80 80 repeat;
-o-border-image: url('http://ift.tt/1EUNiEb') 80 80 80 repeat;
border-image: url('http://ift.tt/1EUNiEb') 80 80 80 repeat;
}




Update


Hi guys,


I think I found something quite similar to what I am imagine. Here is the effect I want : enter image description here


Making a circle from a square image

I've got a simple website for myself and i added square images. I used CSS to make these images a circle and make them rotate as soon as the mouse hovers over them. the problem is that the cirlces aren't completely round. At the top, bottom, left and right a little bit is cut off showing that it used to be a square. I also have bootstrap on so i can make tables. the 3 images are within those tables. The problem is that if i change anything about that it puts the third image under the rest of them. I have been trying alot of things but i just can't fix it. Hope someone here know's better than me. I have a picture but i can't upload it due to my lack of reputation.


CSS Image Shine

I need this image to shine back and forth a few times, not on hover but all the time:


http://ift.tt/1GbonQN



.button {
background:url(http://ift.tt/1Csa1cg);
width:148px;
height:166px;
position:absolute;
top:1px;
left:1px;

}


Thanks


Opencart 2 - more images in latest product

How I can display more images in featured products module? It is posible?


Opencv: 2D barcode (Data Matrix) detection

I am working on detect a 2D Barcode on a PCB board. The environment is Visual Studio 2012.


We met some problems and can’t filter out the 2D barcode image successfully.


Loading the figure: Original Image Size is 1600*1200.


After we load the figure and staring a series of processing as following steps:


1. Finding threshold value by auto-threshold method.


2. Doing binary threshold to image.


3. Doing Opening to make image clearly.


Opening: dst = open(src,element) = dilate(erode(src, element))


4. Filter out the rectangle except the squares. Then we can get a collection of squares. As the following image, after the steps 1-4 we can find squares on the image.


5. Using a similar Data Matrix Template compare with squares respectively by the histogram analysis.


5.1 Calculate the histogram


void calcHist( const Mat* images, int nimages, const int* channels, InputArray mask, OutputArray hist, int dims, const int* histSize, const float** ranges, bool uniform=true, bool accumulate=false );


5.2 Normalize the value range of an array


void normalize( InputArray src, OutputArray dst, double alpha=1, double beta=0, int norm_type=NORM_L2, int dtype=-1, InputArray mask=noArray());


5.3 Compare two histograms with correlation.


double compareHist( InputArray H1, InputArray H2, CV_COMP_CORREL );


6. After the processing we can’t filter the correct image from the square collection.


6.1 We have adjusted the bins of histogram from 256 to 64/32 but the results without robustness, the correlation values are very low even less than 0.5.


6.2 We also try to use the EMD (Earth Mover's Distance) to estimate the similarity of two squares and it’s not solving this problem.


[[Question]]: Is it possible to share us some suggestion to improve our detection method?


Responsive images / browser screen ratio

I've come across this website: http://ift.tt/oZm8D5 and when you scale the page down to tablet size, the logo which is Ethan Marcotte is in perfect ratio when the screen size gets bigger and smaller.


How would I go about replicating the same idea, having an image that is the same perspective no matter what screen resolution or what size the browser window is that it's being rendered on?


Change bufferedImage pixels in java

I have a small problem. I have a BufferedImage which has pixels that have an RGB value. This code is used to create an RGB value from de R, G, B, A values.



private int getRGB(int r, int g, int b, int a){
return (a << 24) | (r << 16) | (g << 8) | b;
}


The first question is, how can i get the R, G, B, A values from a Pixel, because the pixel RGB will return the number that is generated by the code above.


And if I have those values, can I put 2 pixels on top of each other so it calculates the new values or do I have to do that by manual? With automatic calculation you can think of Java 2D when you put 2 transport things on top it will merge the colors.


Thank you very much.


Im trying to compress an image using huffman coding "no built in func allowed"

I've generated the codes for each probability but i cant encode them in the image matrix A, as unit8 cant be transformed to cell matrix. any help please?


< clc; clear all; global CODE A1 = imread('fig2.jpg');



A1=rgb2gray(A1);

A1=imresize(A1,[48 48]);

%imshow(A1)
[M, N]=size(A1);
A = A1(:);
count = imhist(A);
p = count / numel(A);
CODE = cell(length(p), 1);
s = cell(length(p), 1);


for i = 1:length(p) % Generate a starting tree with symbol nodes 1, 2, 3, ... to
% reference the symbol probabilities.
s{i} = i ;
end
while numel(s) > 2
[p, i] = sort(p); % Sort the symbol probabilities
p(2) = p(1) + p(2); % Merge the 2 lowest probabilities
p(1) = []; % and prune the lowest one

s = s(i); % Reorder tree for new probabilities
s{2} = {s{1}, s{2}}; % and merge & prune its nodes
s(1) = [] ; % to match the probabilities
end
makecode(s, [])


for i = 1:numel(CODE)
c = CODE{i};
t = c; c(c=='1') = '0'; c(t=='0') = '1';
CODE{i} = c;

end
%----------------------
function makecode(sc, codeword)
% Scan the nodes of a Huffman source reduction tree recursively to
% generate the indicated variable length code words.

% Global variable surviving all recursive calls
global CODE

if isa(sc,'cell') % For cell array nodes,
makecode(sc{1}, [codeword 0]); % add a 0 if the 1st element
makecode(sc{2}, [codeword 1]); % or a 1 if the 2nd
else % For leaf (numeric) nodes,
CODE{sc} = char('0' + codeword); % create a char code string
end>

I want to develop an android app with internet connectiviyt?how can this be done?

I want to develop an android app with internet connectivity. I need to post regular updates, images and all stuff.How can this type of android app be developed? Do we need to maintain a synch between my sqllite db and server?Please explain me


What can I use to make a row of pictures?

can you tell me what can I use to make a row of pictures like so: http://ift.tt/1xuSVey


I want to be able to select them in order to be able to do other things. Any help would be much appreciated. Thank you!


NavigationDrawer, adapter with an image also

i've got a navigationdrawer with this code for filling:



mDrawerListView.setAdapter(new ArrayAdapter<String>(
getActionBar().getThemedContext(),
R.layout.item_menu,
R.id.item1,
new String[]{
getString(R.string.title_section1),
getString(R.string.title_section2),
getString(R.string.title_section3),
getString(R.string.title_section4),
getString(R.string.title_section5),
getString(R.string.title_section6),
}));


i need to add an image for each item, not only a string. i already have my item xml (R.layout.item_menu):



<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://ift.tt/nIICcg"
android:layout_width="match_parent"
android:orientation="horizontal"
android:weightSum="1"
android:layout_height="wrap_content">
<ImageView
android:layout_width="0dp"
android:layout_weight="0.2"
android:layout_height="wrap_content"
android:adjustViewBounds="true"
android:id="@+id/image1"
android:layout_centerVertical="true" />
<TextView
android:id="@+id/item1"
android:layout_width="0dp"
android:layout_weight="0.8"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceListItemSmall"
android:gravity="center_vertical"
android:padding="5dp"
android:layout_toRightOf="@+id/image1"
android:background="?android:attr/activatedBackgroundIndicator"
android:minHeight="?android:attr/listPreferredItemHeightSmall" />
</LinearLayout>


but i don't know how to pass the image. any help? thanks


Banner image on responsive website overwriting logo and header text on mobile view, how to load image to avoid this?

Currently when my site www.supplementbox.co is viewed on mobile, the banner image becomes overlayed with the logo and header text. On desktop view this isn't a problem. How can I load the image on mobile so as to fix this problem? What's the best solution? Keep in mind I need to keep the same image, but possibly find a way to display it differently. would i need to specify a different image per viewport, or specify to load it differently? how can i solve this problem while maintaing the same image on desktop view?


Android Bitmap image resize

So i have working on a imageview and i want to resize the pictures in my project and i know i can do it with Bitmap so i changed ,y code and began to work Bitmap and when i use the Bitmap resize its throw and eror(exption) and crash from the app



public class ClassicMode extends Activity {//מהמשחק עצמו

String pic;//תמונה של הדגל
Button answer1;//תשובות
Button answer2;
Button answer3;
Button answer4;
TextView guess;//
TextView numOfGuess;//
DatabaseHandler db = new DatabaseHandler(this);
String fn;
Guesses G;
Bitmap bm;
//int Nguess=3;//מסםר ניחושים
//int Nguesstemp=Nguess;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);

guess =(TextView)findViewById(R.id.guesses);
numOfGuess=(TextView)findViewById(R.id.numOfGuesses);
//numOfGuess.setText(Integer.toString(Nguess));
numOfGuess.setText(String.valueOf(Guesses.numOfGuesses));
Flags f = new Flags();
Random r = new Random();//הדגל שיבחר לשאלה
int num = r.nextInt(100);//Up
//Log.d("yes", "yes");
//Random ra = new Random();//הדגלים שיהיו בתשובות
//int numA = ra.nextInt(4);//Up

f = db.getFlag(num);//הצגת הדגל הרנדומלי שיצא
// final Flags d = f; // trying to make it final but it dosent help
fn = f.getName().toString();
pic = f.getImage().toString();
pic_view(pic);//מעבר לפונקציה להשמת התמונה של הדגל במשחק

//מערך ארבע כפתורים כנגד ארבע תשובות
Button [] b = new Button[4];
b[0] = (Button)findViewById(R.id.button1);
b[1] = (Button)findViewById(R.id.button2);
b[2] = (Button)findViewById(R.id.button3);
b[3] = (Button)findViewById(R.id.button4);

List<String>Answers=new ArrayList<String>();//מערך תשובות
Answers.add(f.getName().toString());//הוספת התשובה הנכונה
num = r.nextInt(30);
Answers.add(db.getFlag(num).getName().toString());//הוספת 3 תשובות רנדומליות
num = r.nextInt(30);
Answers.add(db.getFlag(num).getName().toString());
num = r.nextInt(30);
Answers.add(db.getFlag(num).getName().toString());

Collections.shuffle(Answers);//ערבוב התשובות

for(int i=0;i<Answers.size();i++)
{
b[i].setText(Answers.get(i));//השמת התשובות מהמהערך למערך הכפתורים
}
}//end of OnCreat


@SuppressLint("NewApi")
public void resetQuiz()
{
//finish();
recreate();
//numOfGuess.setText(String.valueOf(Nguess));
}

public void check(View v)
{
Log.d("yes", fn);
Button b = (Button)v;
String text = b.getText().toString();
if(text.equals(fn))
resetQuiz();
else
{
if(Guesses.numOfGuesses==1)
{
G.setNumOfGuesses(3);
finish();//כאשר מספר הניחושים
return;
}
Guesses.numOfGuesses--;
//numOfGuess=(TextView)findViewById(R.id.numOfGuesses);
//numOfGuess.setText(Integer.toString(Nguess));
numOfGuess.setText(String.valueOf(Guesses.numOfGuesses));
}

}


@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.second, menu);
return true;
}

private void pic_view(String pic2) {

// TODO Auto-generated method stub
//גישה לדגל לפי שמו וייבוא התמונה
Log.d("Result from pic function " , pic2);
ImageView imageView = (ImageView)findViewById(R.id.imageView1);
String uri ="@drawable/";
uri += pic2;
int imageResource = getResources().getIdentifier(uri, pic2, getPackageName());//הצוות התמונה
Bitmap bm = BitmapFactory.decodeResource(getResources(), imageResource);
Bitmap resized = Bitmap.createScaledBitmap(bm, 120, 120, true);
Drawable res= getResources().getDrawable(imageResource);//ציור התמונה
imageView.setImageDrawable(res);

}


}


the resize and the bitmap and all the image are working in the pic_view function down the code hope u can help me.


picture of my problem with the size so i want to resize the flag: http://ift.tt/1xuQpoC


Safari issue - css background-image inverted color

I have a Safari Issue on my website. The thing is simple : a background-image looks great on Chrome/IE/Firefox...


But my client tell me that on Safari 5.1.10 the background-image is color inverted. I don't use any CSS3.


Any idea ?


http://ift.tt/1OTvpgT


Amazon S3 images not showing on Linkedin or Facebook status update

I have image URL from Amazon S3 - http://ift.tt/1xuOoJc When I try to share this URL on linkedin status update I do not see image thumbnail enter image description here


The same with Facebook. But other images work fine. I think that image was not uploaded correctly on S3, but I do not know what is missed.


Could you point me what can be wrong with the image or how I can validated it?


lundi 30 mars 2015

PNG or JPG (not rgb) over websocket with ArrayBuffer without base64

Is there a way to render PNG to canvas without having to encode images to base64. Server sends png in binary, client receives it in ArrayBuffer and displays it on canvas. Only way i got this is to encode the data to base64 (on server side because I need it to be fast) and send it to client and create an image obj with data:image/png;base64 tag. I know you can create a blog and a file reader but I could not get that to work.


This is the blob version:



var blob = new Blob([image.buffer],{type: "image/png"});
var imgReader = new FileReader();
imgReader.onload = function (e) {
var img = new Image();
img.onload = function (e) {
console.log("PNG Loaded");
ctx.drawImage(img, left, top);
window.URL.revokeObjectURL(img.src);
img = null;

};
img.onerror = img.onabort = function () {

img = null;
};
img.src = e.target.result;
imgReader = null;
}
imgReader.readAsDataURL(blob);


image is Uint8Array. I create a blob from it. The rest is self explanatory.


Images are correct and valid png images. When I send it from the server, I wrote them to file one the server side and they render fine with an image viewer.


Image Gallery View in android

I have the images in url format like this "http://ift.tt/1BZSynT". How can I use these type of images in Gallery View?


PHP Replace multiple parts of a string

I'm building an article poster for my small website, and the problem I've come across is being able to upload images, so I wanted it to be much easier for users by letting them simply dragging images into the article field which would be placed in base64 image format.


What I want to do is once the user is done writing the article, they'll submit it and while it is being submitted, the php script will look for image src instances, grab the base64 image url and execute a script to upload that base64 image and then replace the article html with a http:// url instead of a base64:image URI


Here is the script I'm using to return a url instead of a base64 encoded URI: function get_string_between($string, $start, $end){



$string = " ".$string;
$ini = strpos($string,$start);
if ($ini == 0) return "";
$ini += strlen($start);
$len = strpos($string,$end,$ini) - $ini;
return substr($string,$ini,$len);
}
function generateRandomString($length) {
$characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
for ($i = 0; $i < $length; $i++) {
$randomString .= $characters[rand(0, strlen($characters) - 1)];
}
return $randomString;
}
function base64_to_jpeg($base64_string, $output_file) {

$type = get_string_between($base64_string, "image/", ";");
$output_dir = "../images/";
$output_file = "$output_dir$output_file.$type";
$ifp = fopen($output_file, "wb");

$data = explode(',', $base64_string);

fwrite($ifp, base64_decode($data[1]));
fclose($ifp);

return $output_file;
}
$rand = generateRandomString(17);
$ran = generateRandomString(7);
$tstamp = date("dmyHi");
$output_file = $rand."_".$tstamp."_".$ran;


The above code will be called when the article is being processed after submission, the code below is the code that will check for images within the HTML and if any are present, the base64 will be replaced with real links. Could I have any insight as to what I'm doing wrong with the code below, why they aren't being replaced?



$content = "<div class='article'>This is a random article with multiple images <img src='data:image/png;base64,iVBORw0...' alt='loading.png'/><img src='data:image/png;base64,oHBOsnfjjRw0...' alt='loading.png'/><img src='data:image/png;base64,fejfke...' alt='loading.png'/></div>"

$doc = new DomDocument();
$doc->loadHTML($content);
$sub = $doc->getElementsByTagName("img");
foreach ($sub as $sub) {
$src = $tag->getAttribute('src');
str_replace("$src",base64_to_jpeg($src, $output_file),"$content");

}

$qry = "INSERT INTO article(..,kb_article,..) VALUES(..'$content'..)";
$result = @mysqli_query($GLOBALS["___mysqli_ston"], $qry);

How to change the tag for displaying smiley/emoticons so that the same smiley/emoticon could be displayed on smart devices?

I'm basically a PHP developer by profession. I've no idea about iOS and Android coding at all.


I've developed an API in PHP which returns some data. This data is used by website, iOS app and Android app.


For example, if we take sample output of one such data element it would look as follows :



$feed_status = How are you all boys <img src=\"http://ift.tt/1BZQwnH\" alt=\"Smile\" title=\"Smile\" title=\"v_middle\" />;


If I show this data on a website the smiley/emoticon looks perfect as the <img> tag has got the path for concerned image.


But my issue is when the same data(smiley/emoticon) is displayed on iPhone and Android devices the <img> tag displays as it is. The respective smiley symbol doesn't get appear on these devices.


If you hit the URL : http://ift.tt/1BZQwnH in your browser you could see the respective smiley image.


I want to show the same smiley/emoticon image on smart devices running on iOS and Android. How should I do this? Can someone please help me by providing efficient and optimum solution for this?


Thanks for spending some of your valuable time in understanding my issue.


If you need any further information regarding the issue I'm facing please do let me know. I'd be more than happy to convey you the same.


Thanks in advance.


How to get tap position to add control?

I have a Windows phone 8.0 project that has an image. When the user taps on the image, I have to get the position of the tap and add a text box to this location (above image).


For now, I use the following code, but I always get a wrong position



MessageBox.Show("vao day");
var mp = GetMousePoint(e);
MessageBox.Show("x=" + mp.X + "_" + "y=" + mp.Y);
//x: 258; y:97
double top= 0; double right = 0; double bottom =0; double left=0;
top = e.GetPosition(OrginalImage).Y; //(double)mp.Y - 50;
left = e.GetPosition(OrginalImage).X; //(double)mp.X - 50;

MessageBox.Show("x=" + left.ToString() + "_" + "y=" + top.ToString());
//add textbox to this position
TextBox newtext = new TextBox();
newtext.Text = "truongpm";
newtext.Margin = new Thickness(left, top, right, bottom);
newtext.Width = 124;
newtext.Height = 68;

//button.VerticalAlignment = 234;
//Add contentpanel to your page if there's not one already.
ContentPanel.Children.Add(newtext);
newtext.Visibility = System.Windows.Visibility.Visible;


enter image description here


Can anybody help me please! Thanks


Convert RGB hexsadecimal to 3d matrix in R

I have an RGB image that any cell is a characteristic value like "#FFFFFF". I would like to convert this format to a 3D matrix and use that for image processing and unfortunately I don't now how do that.


Fill SVG image with pattern

I'm trying to fill SVG image with a pattern in HTML, but I'm not successfull. If I fill with the pattern path, it works. But I cannot apply it onto svg image.


Could you help me please? Here is example.


Here is example code:



<svg xmlns="http://ift.tt/nvqhV5" xmlns:xlink="http://ift.tt/PGV9lw" xmlns:ev="http://ift.tt/IIyxi6" width="400" height="400">
<defs>
<pattern id="image" x="0" y="0" width="400" height="400" patternUnits="userSpaceOnUse">
<image x="0" y="0" xlink:href="latka.jpg" width="100" height="100" />
</pattern>
</defs>
<image x="0" y="0" width="400" height="400" xlink:href="kosile.svg" fill="url(#image)"/>
</svg>

opencv printing weird black images

opencv imwrite is printing weird black(ish) images in my C++ code. An example code to read an image and then print it out is following:



#include "iostream"
#include "opencv2/core/core.hpp"
#include "opencv2/highgui/highgui.hpp"
using namespace std;

int main()
{
cv::Mat input_image = cv::imread("input_image.tiff",0);
cv::imwrite("output_image.tiff",input_image);

return 0;
}


I compile it as g++ -std=c++11 main.cc -o bin `pkg-config --cflags --libs opencv`


The input image and output image are as follows (should be the same):


Input Image Input Image Output Image Output image


The image is being read correctly as I have checked it by accessing different pixel values.Therefore the problem is in imwrite.


Extra Info: The code was working fine in the beginning but suddenly changed its behavior, reinstalling opencv and its libraries doesn't help.


Can someone please tell what is wrong here,


Thanks


Pyscreenshot returns black screen

Trying to take a screenshot with pyscreengrab, following their documentation. However, it only returns black boxes for me. I've seen a couple other people comment with the same issue but haven't seen any resolution. Happens when using show() or grab_to_file(), as well as with fullscreen or bounding box.


Code:



import pyscreenshot as ImageGrab

#testing save functionality
ImageGrab.grab_to_file('testImage.png')

#testing show functionality
im = ImageGrab.grab()
im.show()


OSX 10.10.2


Python 2.7.6


The only alternative I know of is using the os.system(screencapture) method. If that is a better route to go I can do that, but I would like to know why pyscreenshot isn't working. I also don't know if there are performance advantages/disadvantages to using pyscreenshot vs os.system repeatedly.


Display images in Django

I have a django app which allows users to submit an image with it. Right now my model looks like



class Posting(models.Model):
title = models.CharField(max_length=150)
images = models.ForeignKey(Image, null=True)

class Image(models.Model):
img = models.ImageField(upload_to="photos/",null=True, blank=True)


and I am trying to display the images in my template however I cannot seem to get it to work. I have gone though countless stack overflow posts and haven't had any luck. In my template I have



{ for post in postings }
<img src"{{ post.image.url }} #and many variations of this


however other seems to display the url. The url seems to always be blank. Any help would be greatly appreciated!


What order does PixelGrabber put pixels into the array in java?

What order does PixelGrabber put pixels into the array in java? Does it take the pixels along the width of the image first? Or along the height of the image first?



public static int[] convertImgToPixels(Image img, int width, int height) {
int[] pixel = new int[width * height];
PixelGrabber pixels = new PixelGrabber(img, 0, 0, width, height, pixel, 0, width);
try {
pixels.grabPixels();
} catch (InterruptedException e) {
throw new IllegalStateException("Interrupted Waiting for Pixels");
}
if ((pixels.getStatus() & ImageObserver.ABORT) != 0) {
throw new IllegalStateException("Image Fetch Aborted");
}
return pixel;
}

Display image on top of gif

I have a gif centered in the a middle of a webpage. Once the gif stops playing I want to display three icons on top of the gif and have them light up when users hover over them. How do go about coding the images so they are visible only when the gif has completed loaded/played? Is it possible to do this without javascript?


Inserting images to an Excel sheet in Delphi

I have a question here, I have an application and I need to add images to it. I have tried:



Sheet.Shapes.AddPicture(G_V.Prog_Dir+'pic.BMP',false,true, 190, 10+(15*rowcount), 100, 100 );


it works just fine, but I don't want to give parameters, I want to insert pictures to specified (and parametric) cells because I need to add picture to the last column of the page; this excel needs to be printed I must mention that. So I tried:



Sheet.Range['E'+inttostr(rowcount),'E'+inttostr(rowcount)].Select;
Sheet.Pictures.Insert(G_V.Prog_Dir+'pic.BMP');


It looks OK at first sight, however I think this code links images to the sheet. For example, I send the created Excel to another computer and these images cannot be seen (I don't recall the exact error) and when I searched it, I found out that receiving computer needs to have images at the exact path. As a solution to this, "Sheet.Shapes.AddPicture" recommended but as I stated before, I need another solution here.


I didn't see anybody experiencing this kind of problem, I hope someone helps me out.


Annoying Python Image.pixel method issue

so I'm just trying to learn how to use the Image module and for some reason PyCharm won't recognize the Image.Pixel method, even after I've imported the Image module. An easy question, I'm sure, but What am I doing wrong here? (I've installed PIL)


from PIL import Image


p = Image.Pixel(45, 76, 200)


print(p.getRed())


PyCharm tells me 'ImportError: No module named 'Pixel', but from what I've read here (http://ift.tt/1G9QP5q), I don't really see why this isn't working...


thanks in advance guys.


Trying to find large image package to download

What I am looking for is a download file containing hundreds if not thousands of images. I need the images to be in the range of 1x1 to 10x10 pixels (or close) and each image to be a random color.


So Pretty much a photo cut into thousands of pixels (smaller images). I'm sure there is something out there like this but I've tried searching for something but I'm not having any luck.


Thanks if you can help!


Processing mirror image over x axis?

I was able to copy the image to the location but not able to mirror it. what am i missing?



PImage img;
float srcY;
float srcX;
int destX;
int destY;

img = loadImage("http://ift.tt/19iOGYC Beach-State-College2-e1329949470871.jpg");

size(img.width, img.height * 2);

image(img, 0, 0);
image(img, 0, 330);

int num_pixels = img.width * img.height;

int copiedWidth = 319 - 254;
int copiedHeight = 85 - 22;
int startX = (width / 2) - (copiedWidth / 2);
int startY = (height / 2) - (copiedHeight / 2);

Simple CSS image cross-fading acting weird

I am trying to create a very simple image cross fade effect with four different pictures. It should go smoothly from 1st to the 2nd, from 2nd to 3rd, 3rd to 4th and then back to the 1st.


This is the code I am using:


HTML:



<div class="css-slideshow">
<figure>
<img src="test1.jpg"/>
</figure>
<figure>
<img src="test2.jpg"/>
</figure>
<figure>
<img src="test3.jpg" />
</figure>
<figure>
<img src="test4.jpg" />
</figure>
</div>


...and CSS:



figure:nth-child(1) {
-webkit-animation: xfade 12s 9s infinite;
}
figure:nth-child(2) {
-webkit-animation: xfade 12s 6s infinite;
}
figure:nth-child(3) {
-webkit-animation: xfade 12s 3s infinite;
}
figure:nth-child(4) {
-webkit-animation: xfade 12s 6s infinite;
}


@-webkit-keyframes xfade{
0% { opacity:1; }
19% { opacity:1; }
25% { opacity:0; }
94% { opacity:0; }
100% { opacity:1; }
}


The idea is the whole sequence should take 12 seconds.


The first loop looks great, the transitions are smooth, everything works like a charm. However, with the start of the second, and any other loop, it looks like it's not fading directly to the next image, but sort of through the white background. You can spot a "flash" while fading.


Can you help me? I am guessing the problem lays somewhere in that percentage, but I'm not sure.


Thank you


How to make IMG in LI stack regardless of height

Example Site


What I am running into is that my images only stack on the right side. Now I would like to have it on both, but it seems the left side is connecting to the right side images. How can I fix the left side so it stacks like the right?


HTML snipet:



<li class="searchable" data-index="TAG"><dl>
<dt><img src="IMAGE"></dt>
<dt>CAPTION</dt></dl></li>


CSS Snipet:



dl{
color: yellow;
font-size: 30px;
}



li {
float: left;
list-style-type: none;
padding-left: 50px;
padding-bottom:20px;
}

img{
width: 400px;
background-color: rgba(144,144,144,.3);
box-shadow: 0px 0px 15px black;
}


~Xplo


What is needed to create a dynamic print preview?

i would like to achieve a dynamic print preview like the one you can see at http://ift.tt/1bKQ0Fc I mean the preview that changes when you select for example the size of the mat or the frame.


Image is partially downloading,

I cannot download the file in following url: http://ift.tt/1Hf92xf


Only a part of the file is being downloaded.


Following is my code. Please let me know if I'm doing anything wrong.



URLConnection urlConn = new URL( "http://ift.tt/1Hf92xf").openConnection();
InputStream is = urlConn.getInputStream();
FileOutputStream fos = new FileOutputStream( file.getPath() );

byte[] buffer = new byte[4096];
int len;

while( ( len = is.read( buffer ) ) > 0 )
{
fos.write( buffer, 0, len );
}

Where to find/buy graphics to use in apps?

So I'm building my first app (a hockey app), and in a few hockey apps I've downloaded, I realized that some of the same graphics are used. For example, there is an identical ice skate that two unrelated apps are using. I've searched for where to find or buy the rights to this graphic (both for retina @2x and non-retina displays), among other graphics, and have come up short. I'm also wondering how to use photographs in the background--do I just use the image as a png or jpg? Thank you.


Is it possible to make a torn paper effect on edges of a picture

I remember that I saw a beautifully designed website, there is a picture in the background and the edges of this picture look like torn paper effect which is fantastic!


I searched the similar questions here but it turns out that the effects in the answers are primitive, which are very simple rugged black lines.


What I want: 1. I want this picture to be as wide as the device screen which means responsive. 2. the edges of this picture look like torn paper 3. I will place this picture as a banner after the Top Navigation bar but before the content


It should look like the white area in this picture. But in my case, I will need to fill in my picture to replace the white area.


enter image description here


Here is my code: Notice: in this code, the css uses an image as the edge, BUT that is not want I want. I just want the edges be the picture itself.(Is this possible?) So it will look like this one(the one on the right side, you can see that there is no white rugged edges) enter image description here



<div class="row">
<div id="letter" class="col-lg-12 col-md-12 col-sm-12 col-xs-12">

</div>
</div>

#letter { /*torn paper border*/
height:450px;
position:relative;
top:0;
bottom:0;
left:0;
right:0;
background-image:url('img/background.jpg');
background-size:cover;
opacity:0.8;
border-style: solid;
border-width: 40px 40px 40px;
-moz-border-image: url('http://ift.tt/1EUNiEb') 80 80 80 repeat;
-webkit-border-image: url('http://ift.tt/1EUNiEb') 80 80 80 repeat;
-o-border-image: url('http://ift.tt/1EUNiEb') 80 80 80 repeat;
border-image: url('http://ift.tt/1EUNiEb') 80 80 80 repeat;
}

Is there a Grunt Task to Add a Background Image to All Images in Folder?

Background


I have a large number of employee images for a website. Each one is a headshot, and the area around the head is transparent:


enter image description here


On the website, I apply a background-image to each img.



<img class="employee" src="employee_x.jpg" />

.employee {
background:url('employee_background.jpg') center center / cover;
}


It ends up looking like:


enter image description here


This lets me easily change out the images in the future, for all of them. Problem is, the background downloads first and the site owner is complaining that it looks fake when the background loads first.




Problem


I now need to combine all of them and resave the images, with the backgrounds and employee images saved together. I can do this with Photoshop or Paint.net, but it takes a lot of time to go through every single image.




Goal


I want it to take a folder with employee_background.jpg and all the other employee photos and then resave all of them into a production folder, using the background.



employees/john_smith.png
employees/sally_norton.png
employees/bill_miller.png
employees/employee_background.jpg

---->

employees/production/john_smith.png
employees/production/sally_norton.png
employees/production/bill_miller.png
employees/production/employee_background.jpg


Is there a Grunt task that can do this for me?


Wordpress - Pulling in dynamic category images to a li

I'm running into a problem pulling in category images in dynamically to a li. Im kinda new to Wordpress and have no issues building the theme but sometimes run into issues pulling in the content I need. Heres what i'm looking to do.


I have a section on this site(http://ift.tt/19p2XTy) "News Topics". Each icon (image box) will be a category and the image will be associated with the category. Im going to use ACF to attach the image to the category but I need to be able to pull those images into the li dynamically and each time a new category and image is added in the back end, it needs to just automatically load on this list. I also need to be able to EXCLUDE some categories that don't belong on their. For instance the homepage hero slideshow is loaded via a category, so I would need to leave that category off the list. When that image is clicked it also needs to load the category title and description in the blue box below.


So this is my problem i'm trying to solve. If anyone could steer me in the right direction I would be very grateful.


Thanks -Dan


jqPlot axes and legend is not rendering properly in exported image

my jqPlot is rendering properly but when it is exported as an image, the axes text and legend labels are not rendered properly in the image. The text is moving right.


Here is my actual plot


Actual plot


Here is the exported image


enter image description here


Is it possible to apply some CSS to fix this?


Thanks a lot.


UIActivity customized not show icon iOS 7

I customized a UIActivity, in iOS 8 everything is perfect:


enter image description here


But in iOS 7 it doesn't show the images:


enter image description here


I have all methods that need to construct a UIActivity and when executed in iOS8 the share works.


What is the image format with ZOMG file signature?

There was a file with a png extension in an Android APK archive, it wouldn't open in any image media player and notepad shows the first 4 bytes are ZOMG, do you have any idea of the file format or how I can find out the format?