Get image

getWidth and getHeight are predefined abstract methods present in Image class. getWidth method determines the width of an image. getHeight method determines the height of an image. Return type of this two method are int type. Syntax- public abstract int get Width (java.awt.image.    ImageObserver) public abstract int get Height java.awt.image. ImageObserver).

setFont and setColor are predefined abstract methods present in Graphics class. These methods are used to set the font and color of the graphics     context respectively. Syntax-public abstract void setFont (java.awt.Font) public abstract void setColor (java.awt.Color).

 

Here is the Java Example for GetImageSizeExample:


import java.awt.*;  
import java.awt.event.*;
import java.util.Locale;
public class GetImageSizeExample extends Frame
{
         Image image;
         String Picture = "DineshThakur.jpg";
         String Name = "Dinesh Thakur";
         int width,height;
         public GetImageSizeExample()
     {
         addWindowListener(new WindowAdapter()
            {
                 public void windowClosing(WindowEvent e)
                  {
                        System.exit(0);
                   }
   &.
sp;                image = tool.getImage(Picture);
                     width=image.getWidth(this);
                     height=image.getHeight(this);
                     this.setSize(width+320,height+250);
                     g.drawImage(image,150,120,this);
                     g.setColor(new Color(0,0,180));
         &n.
bsp;                 g.drawString("My Pic Size: "+width+ "*"+height,135, height+160);
                }
                   public static void main(String args[]) throws Exception
                    {
                       GetImageSizeExample GIS = new GetImageSizeExample();
                       GIS.setVisible(true);
                       GIS.setSize(350,250);
                       GIS.setLocation(200, 100);
                    }
}


find out the image size

ecomputernotes.com

Основная информация

В 1993 году Getty Images начало деятельность как фотоагенство. В начале двухтысячных годов компания купила сервис Image.net, а в 2006 микросток iStockphoto.

Эти сайты принадлежат Getty Images и сейчас. На 2016 год в архиве фотобанка 80 млн изображений.

Стоит отметить, что это закрытый фотобанк, и стать внештатным фотографом компании можно только по приглашению. Это и отличает Getty Images от других фотостоков.

Плюсы сервиса:

высокие выплаты;

подтверждение статуса эксперта.

Минусы:

сотрудничество только по приглашению;

жесткие требования к фотографиям.

Требования к загружаемым работам

Если вы работали с iStockphoto, и считаете их требования завышенными, то на Getty Images вам точно рано. У компании нет четких требований к изображениям, соблюдая которые вы точно попадете на сайт. Известно одно — эти работы должны быть реально крутыми, а не шаблонными.


Однако есть фотографии, которым отдаются предпочтения. Один из таких жанров — так называемые travel-фото — изображения разных стран или достопримечательностей.

Однако если хотите узнать подходят ли ваши работы для Getty Images, изучите конкурентов. Возьмите свое лучшее фото и идите на gettyimages.com. Ищите в поиске свою тему и если найденные фото лучше ваших, то в команду фотобанка вам пока что рано. Если же ваши изображения конкурентоспособные, то можно постараться пробиться на сайт. Как? Узнаете немного позже.

Цены и способы оплаты

Конкретных цен на сайте нет. Вы можете подать одно фото двадцать раз и заработать 80$, а можете сделать единственную продажу и получить за нее 1000$. Ваши работы могут долго лежать впустую и без покупок, а потом у вас неожиданно приобретут фото за 800$. Такое на Getty Images происходит часто.

Чтобы узнать сколько получает фотограф, посмотрите цены фотографий, которые выставлены на сайте на сегодняшний день. Автор получает 30–50% от стоимости изображения. Так что посчитать прибыль с одной работы не тяжело.

Заработанные средства сервис выплачивает раз в месяц, чеком или с помощью системы PayPal. Минимальна сумма для вывода 50$.

Регистрации на Getty Images

Стать автором на сайте можно только по приглашению. Вы не можете пройти регистрацию на Getty Images и начать выставлять фото. Но если ваши работы хорошие, то компания сама вас найдет и предложит сотрудничать. Чтобы это произошло как можно быстрее вам нужно привлечь внимание фотобанка.


Первое место, где можно показать себя — iStockphoto. Этот микросток принадлежит Getty Images. Поэтому регистрируйтесь там как автор и начинайте прокачивать свой аккаунт. Если у вас действительно хорошие работы, то рано или поздно с вами свяжутся.

Второй вариант более быстрый и действенный. Getty Images часто устраивают конкурсы фотографов. Узнать о соревнованиях, которые проходят сейчас, можно здесь: http://competitions.gettyimages.com/. Чтобы заявить о себе вам нужно проявить талант в одном из таких конкурсов. Лучших фотографов Getty Images приглашают к сотрудничеству
Заключение

Если задаться целью, то попасть на Getty Images реально. Нужно просто все работы ориентировать на этот фотобанк. И если уж вам пришло письмо от этой компании, можете считать себя фотографом-экспертом. Тот, кто работал с Getty Images на остальных фотобанках не будет иметь проблем.

fotostock.org

android_camera1.png

How to get image from Gallery

Android device has Gallery application installed by default which contains images and videos. It is the place where the images and videos you download from internet or upload from your computer can be viewed.

Lets see how you can use the Gallery to pick a photo for your application.

First create a layout with a Button
and an ImageView.

 <?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"  xmlns:app="http://schemas.android.com/apk/res-auto"  xmlns:tools="http://schemas.android.com/tools"  android:layout_width="match_parent"  android:layout_height="match_parent">   <Button  android:onClick="pick"  android:text="Pick"  android:layout_centerHorizontal="true"  android:layout_width="wrap_content"  android:layout_height="wrap_content" />   <ImageView  android:id="@+id/iv"  android:layout_centerInParent="true"  android:layout_width="200dp"  android:layout_height="200dp" />  </RelativeLayout> 

Next use following snippet for photo picker.

 public class MainActivity extends AppCompatActivity {  private static final int PICK_IMAGE_REQUEST = 100;  private ImageView iv;   @Override  protected void onCreate(Bundle savedInstanceState) {  super.onCreate(savedInstanceState);  setContentView(R.layout.activity_main);   iv = (ImageView) findViewById(R.id.iv);  }   public void pick(View v) {  Intent intent = new Intent(Intent.ACTION_GET_CONTENT);  intent.setType("image/*"); .    
tream = getContentResolver().openInputStream(selectedImage); // Bitmap yourSelectedImage = BitmapFactory.decodeStream(imageStream); // imageStream.close(; // iv.setImageBitmap(yourSelectedImage); //} catch (FileNotFoundException e) { // e.printStackTrace(); //} // method 3 // iv.setImageURI(selectedImage); } break; } } }

If you’re wondering why I used ACTION_GET_CONTENT and not ACTION_PICK, then the answer lies here.

Sometimes it’s useful to get full path to image from Gallery. For this purpose use following auxiliary class

 public class ImageFilePath {  @SuppressLint("NewApi")  public static String getPath(final Context context, final Uri uri) {  //check for KITKAT or above  final boolean isKitKat = Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT;   // DocumentProvider  if (isKitKat && DocumentsContract.isDocumentUri(context, uri)) {  // ExternalStorageProvider  if (isExternalStorageDocum.    
); return getDataColumn(context, contentUri, null, null); } // MediaProvider else if (isMediaDocument(uri)) { final String docId = DocumentsContract.getDocumentId(uri); final String[] split = docId.split(":"); final String type = split[0]; Uri contentUri = null; if ("image".equals(type)) { contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI; } else if ("video".equals(type)) { contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI; } else if ("audio".equals(type)) { contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI; } final String selection = "_id=?"; final String[] selectionArgs = new String[] { split[1] }; return getDataColumn(context, contentUri, selection, selectionArgs); } } // MediaStore (and general) else if ("content".equalsIgnoreCase(uri.getScheme())) { // Return the remote address if (isGooglePhotosUri(uri)) return uri.getLastPathSegment(); return getDataColumn(context, uri, null, null); } // File else if ("file".equalsIgnor.
getString(index); } } finally { if (cursor != null) cursor.close(); } return null; } public static boolean isExternalStorageDocument(Uri uri) { return "com.android.externalstorage.documents".equals(uri.getAuthority()); } public static boolean isDownloadsDocument(Uri uri) { return "com.android.providers.downloads.documents".equals(uri.getAuthority()); } public static boolean isMediaDocument(Uri uri) { return "com.android.providers.media.documents".equals(uri.getAuthority()); } public static boolean isGooglePhotosUri(Uri uri) { return "com.google.android.apps.photos.content".equals(uri.getAuthority()); } }

Usage

 if(resultCode == RESULT_OK){  Uri selectedImage = data.getData();  String path = ImageFilePath.getPath(activity.getApplicationContext(), selectedImage); } 

How to get image from Camera

Open your AndroidManifest.xml file where we add permission to access camera and write external storage.

 <uses-feature android:name="android.hardware.camera" android:required="true" /> <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/> <uses-permission android:name="android.permission.CAMERA"/> 

Lets see how you can use the camera to take a photo for your application.

First create a layout with a Button and an ImageView.

 <?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"  xmlns:app="http://schemas.android.com/apk/res-auto"  xmlns:tools="http://schemas.android.com/tools"  android:layout_width="match_parent"  android:layout_height="match_parent">   <Button  android:onClick="take"  android:text="Take"  android:layout_centerHorizontal="true"  android:layout_width="wrap_content"  android:layout_height="wrap_content" />   <ImageView  android:id="@+id/iv"  android:layout_centerInParent="true"  android:layout_width="200dp"  android:layout_height="200dp" />  </RelativeLayout> 

Next use following snippet to take photo from camera. The take picture button in activity will fire an ACTION_IMAGE_CAPTURE intent to open the camera, after a picture is taken and saved, it will return to this activity calling the onActivityResult method will be called.

 import android.Manifest; public class MainActivity extends AppCompatActivity {  private static final int CAMERA_TAKE_REQUEST = 200;  private final static int ALL_PERMISSIONS_RESULT = 101;  private ImageView iv;  File file;  Uri uri;  private Context context;  private Activity activity;  ArrayList<String> permissions = new ArrayList<>();  ArrayList<String> permissionsToRequest;  ArrayList<String> permissionsRejected = new ArrayList<>();   @Override  protected void onCreate(Bundle savedInstanceState) {  super.onCreate(savedInstanceState);  setContentView(R.layout.activity_main);   iv = (ImageView) findViewById(R.id.iv);   context = this;  activity = MainActivity.this;   permissions.add(Manifest.permission.CAMERA);  permissions.add(Manifest.permission.WRITE_EXTERNAL_STORAGE);  permissionsToRequest = findUnAskedPermissions(permissions);  }   @TargetApi(Build.VERSION_CODES.M)  public void take(View v) {  if(checkCameraExists()) {  if (permissionsToRequest.size() > 0) {  requestPermissions(permissionsToRequest.toArray(new String[permissionsToRequest.size()]),  ALL_PERMISSIONS_RESULT);  } else {  Toast.makeText(context,"Permissions already granted.", Toast.LENGTH_LONG).show();  launchCamera();  }  } else {  Toast.makeText(activity, "Camera not available.", Toast.LENGTH_SHORT).show();  }  }   public boolean checkCameraExists() {  return activity.getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA);  }   private void launchCamera() {  Intent intent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);   file = new File(Environment.getExternalStorageDirectory(), String.valueOf(System.currentTimeMillis()) + ".jpg");  uri = FileProvider.getUriForFile(activity, activity.getApplicationContext().getPackageName() + ".provider", file);  intent.putExtra(android.provider.MediaStore.EXTRA_OUTPUT, uri);   startActivityForResult(intent, CAMERA_TAKE_REQUEST);  }   @Override  protected void onActivityResult(int requestCode, int resultCode, Intent data) {  switch(requestCode){  case CAMERA_TAKE_REQUEST:  iv.setImageURI(android.net.Uri.parse(file.toURI().toString()));  break;  }  }   //  // Permissions  //   private ArrayList findUnAskedPermissions(ArrayList<String> wanted) {  ArrayList result = new ArrayList();   for (String perm : wanted) {  if (!hasPermission(perm)) {  result.add(perm);  }  }   return result;  }   private boolean hasPermission(String permission) {  if (canAskPermission()) {  if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {  return (checkSelfPermission(permission) == PackageManager.PERMISSION_GRANTED);  }  }  return true;  }   private boolean canAskPermission() {  return (Build.VERSION.SDK_INT > Build.VERSION_CODES.LOLLIPOP_MR1);  }   @TargetApi(Build.VERSION_CODES.M)  @Override  public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {  switch (requestCode) {  case ALL_PERMISSIONS_RESULT:  for (String perms : permissionsToRequest) {  if (!hasPermission(perms)) {  permissionsRejected.add(perms);  }  }   if (permissionsRejected.size() > 0) {  if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {  if (shouldShowRequestPermissionRationale(permissionsRejected.get(0))) {  String msg = "These permissions are mandatory for the application. Please allow access.";  showMessageOKCancel(msg,  new DialogInterface.OnClickListener() {  @Override  public void onClick(DialogInterface dialog, int which) {  if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {  requestPermissions(permissionsRejected.toArray(  new String[permissionsRejected.size()]), ALL_PERMISSIONS_RESULT);  }  }  });  return;  }  }  } else {  Toast.makeText(context, "Permissions garanted.", Toast.LENGTH_LONG).show();  launchCamera();  }  break;  }  }   private void showMessageOKCancel(String message, DialogInterface.OnClickListener okListener) {  new AlertDialog.Builder(activity)  .setMessage(message)  .setPositiveButton("OK", okListener)  .setNegativeButton("Cancel", null)  .create()  .show();  } } 

Android 7.0 Nougat introduced some file system permission changes in order to improve security. If you’ve already updated your app to targetSdkVersion 24 (or higher) and you’re passing a file:// URI outside your package domain through an Intent, then what you’ll get is a FileUriExposedException.

So, Android may throw FileUriExposedException in Android 7.0 (API level 24) and above, this exception will come when you will expose a file:// URIs outside your package domain through Intent.

FileProvider is a special subclass of ContentProvider which allows us to securely share file through a content:// URI instead of file:// one. Why is this a better approach? Because you’re granting a temporary access to the file, which will be available for the receiver activity or service until they are active/running.

We create our own class inheriting FileProvider in order to make sure our FileProvider doesn’t conflict with FileProviders declared in imported dependencies as described here.

Add a class extending FileProvider

 public class GenericFileProvider extends FileProvider {} 

Next, add the GenericFileProvider in our AndroidManifest.xml:

 <manifest>  ...  <application>  ...  <provider  android:name=".GenericFileProvider"  android:authorities="${applicationId}.provider"  android:exported="false"  android:grantUriPermissions="true">  <meta-data  android:name="android.support.FILE_PROVIDER_PATHS"  android:resource="@xml/file_provider_paths" />  </provider>  ...  </application> </manifest> 

We’re going to set android:exported to false because we don’t need it to be public, android:grantUriPermissions to true because it will grant temporary access to files and android:authorities to a domain you control, so if your domain is me.proft.superapp then you can use something like me.proft.superapp.provider. The authority of a provider should be unique and that’s the reason why we are using our application ID plus something like .provider.

Then we need to create the file_provider_path in the res/xml folder. That’s the file which defines the folders which contain the files you will be allowed to share safely. In our case we just need access to the external storage folder:

 <?xml version="1.0" encoding="utf-8"?> <paths>  <external-path name="external_files" path="." /> </paths> 

The final step is to change the line of code below in

 File file = new File(Environment.getExternalStorageDirectory(), String.valueOf(System.currentTimeMillis()) + ".jpg");  Uri photoURI = Uri.fromFile(file); 

to

 Uri photoURI = FileProvider.getUriForFile(context, context.getApplicationContext().getPackageName() + ".provider", file); 

If you’re using an Intent to make the system open your file, you may need to add the following line of code:

 intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 

Instead of using Uri.fromFile(file) we create our URI with FileProvider.getUriForFile(context, string, file) which will generate a new content:// URI with the authority defined pointing to the file we passed in.

Useful links

  • Android Camera1 API guide
  • Android working with Camera2 API
  • android-Camera2Basic
  • PixImagePicker

en.proft.me

How to get image resource id from image name is one of the challenges we face why developing for android.

Imagine that you have some images stored in the drawable folder and also in local SQLite database. The images are stored with their names in the database. If you want to fetch the image names from the database and in other to use them in your ImageView you need to get the image resource id from the names of the images.

The question in your mind now is if there is any way to find image resource id from image name.

This is how we can get image resource id from image name.

1. Create a new android app

Go to File menu

Click on New menu

Click on Android Application

Enter Project name: AndroidImageNameToId

Package: com.inducesmile.androidnametoid

Select Empty Activity

Name your activity: MainActivity

Keep other default selections

Continue to click on next button until Finish button is active, then click on Finish Button.

2. Add the code below to activity_main.xml layout file

<?xml version="1.0" encoding="utf-8"?>
<?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"  xmlns:tools="http://schemas.android.com/tools"  android:id="@+id/activity_main"  android:layout_width="match_parent"  android:layout_height="match_parent"  android:paddingBottom="@dimen/activity_vertical_margin"  android:paddingLeft="@dimen/activity_horizontal_margin"  android:paddingRight="@dimen/activity_horizontal_margin"  android:paddingTop="@dimen/activity_vertical_margin"  tools:context="com.inducesmile.androidimageresourceid.MainActivity">  <ImageView  android:id="@+id/image_name_to_id"  android:layout_width="wrap_content"  android:layout_height="wrap_content"  android:layout_centerHorizontal="true"  android:layout_centerVertical="true"  android:scaleType="centerCrop"  android:contentDescription="@string/app_name"/> </RelativeLayout>

In this tutorial, I am using image named profiles.png which is inside the drawable folder

4. Update your MainActivity.java file

You can see that we are using the name of the image and we also called a method that returns its id. With the image id, pass it as a parameter to ImageView setImageResource(int id) method.

import android.content.Context; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.widget.ImageView; public class MainActivity extends AppCompatActivity {  @Override  protected void onCreate(Bundle savedInstanceState) {  super.onCreate(savedInstanceState);  setContentView(R.layout.activity_main);  ImageView imageNameToId = (ImageView)findViewById(R.id.image_name_to_id);  int imageId = getResourseId(this, "profiles", "drawable", getPackageName());  imageNameToId.setImageResource(imageId);  }  public static int getResourseId(Context context, String pVariableName, String pResourcename, String pPackageName) throws RuntimeException {  try {  return context.getResources().getIdentifier(pVariableName, pResourcename, pPackageName);  } catch (Exception e) {  throw new RuntimeException("Error getting Resource ID.", e);  }  } }

That is simply a way to get image resource id from image name. If you have used another method to achieve it, I will appreciate it if you can share your solution with us.

inducesmile.com

imagesx() and imagesy()

The imagesx() and imagesy() are used to extract the width and height of the images respectively. For that, it accepts the resource type of data which will be returned on creating new images dynamically using PHP script. For example, PHP captcha code is created dynamically as images to ensure that the input of web application is entered by the human. If we want to check the width and height of the captcha we have created, then, imagesx() and imagesy() could be used appropriately.

php_get_image_properties

getimagesize()

This PHP method that returns an array of image properties like width, height, image type, mime type and etc. This method will return a limited amount of image data. But, there is no need to send resource data of the image as the argument of this function. Rather, we should specify the path of the image file, which can be either relative or absolute path.

The following PHP program is used to extract the properties of an image. For that, we need to access HTML form data on submitting the selected image file.

First, create HTML content to select the image file for which we need to extract properties. As we have seen, to upload files through HTML form, we need to specify the enctype attribute to the form. But this attribute can be used, if the form method is posted, as like as the following content.

<html>  <head>  <title>Getting Image Properties</title>  </head>  <body>  <form name="frmImage" action="" method="post" enctype="multipart/form-data">  <input type="file" name="myImage" />   <input type="submit" name="submit" value="Submit" />  </form>  </body>  </html>

After that, we need to access these from data from a PHP script to be embedded on top of the above content. And the PHP script is,

<?php  if(isset($_POST["submit"])) {  if(is_array($_FILES)) {  $image_properties = getimagesize($_FILES['myImage']['tmp_name']);  print "<PRE>";  print_r($image_properties);  print "</PRE>";  }  }  ?>

This script will be executed on submitting the form, and the image file is added to PHP global array, that is, $_FILES. After ensuring that the $_FILES is not empty, then, we should specify the name of the file to getimagesize() as shown above. Finally, image properties are returned as an array and displayed to the browser, in human readable format, by using PHP print statement inside pre tags.

Array  (   [0] => 1024   [1] => 768   [2] => 2   [3] => width="1024" height="768"   [bits] => 8   [channels] => 3   [mime] => image/jpeg  )

exif_read_data()

Since getimagesize() functions will return limited set of properties, exif_read_data() is used to get more information further associated with images. So, added to the width, height information, it will return a huge list of additional information such as image created date, last modified date, File name, size, orientation, resolution and etc.

This function will be used to extract properties of digital images in which Exif data is stored in its header. Exif is a standard format, that can be expanded as Exchangeable Image Format.

Image types are of 16 totally, which varies based on the devices used to capture images. Image types are returned as numbers that are associated with the available types of images like gif, png and etc. For example, if image type returned as 2 denotes that, it is JPEG image.

Not only the type of the images but also the entire list of image properties returned by this function, will also be varied depends on devices.

In the above program, replace the line which invokes getimagesize() function, that is,

$image_properties = getimagesize($_FILES['myImage']['tmp_name']);

by the following line for getting image properties in EXIF format.

$image_properties = exif_read_data($_FILES['myImage']['tmp_name']);

And, let us experiment with different images captured by different devices, to see the differences between the resultant property array will be returned.

↑ Back to Top

phppot.com


You May Also Like

About the Author: admind

Добавить комментарий

Ваш e-mail не будет опубликован. Обязательные поля помечены *

Этот сайт использует Akismet для борьбы со спамом. Узнайте как обрабатываются ваши данные комментариев.

Adblock
detector