Can I display a image in custom layout? - android

I know I can use the below code to display a image in system layout,
but I hope to display an image in my custom layout, how can I do that? Thanks!
public void onClick(View v) {
// TODO Auto-generated method stub
int id = v.getId();
Intent intent = new Intent();
intent.setAction(Intent.ACTION_VIEW);
intent.setDataAndType(Uri.parse("file://" + arrPath[id]), "image/*");
startActivityForResult(intent,ForBrowse);
}
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#drawable/border_ui"
android:orientation="vertical"
android:paddingTop="3dip" >
<ImageView
android:id="#+id/imageView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1" />
<Button
android:id="#+id/btnClose"
style="#style/myTextAppearance"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="#string/myreturn" />
</LinearLayout>

If the above resolutions are not ok, then try this one, it loads the image from tha page you want:
String url = "file://" + arrPath[id]), "image/*";
Bitmap bmp = fromURL(url);
imgview.setImageBitmap(bmp);
and write this function:
public static Bitmap fromURL(String src) {
try {
URL url = new URL(src);
HttpURLConnection connection = (HttpURLConnection) url
.openConnection();
connection.setDoInput(true);
connection.connect();
InputStream input = connection.getInputStream();
Bitmap mybitmap = BitmapFactory.decodeStream(input);
return bitmap;
} catch (Exception exception1) {
return null;
}

after setting the xml up as you have done,
simply add the following code to set image to your imageview
ImageView img = (ImageView)findViewById(R.id.Imageview1);
img.setImageResource(R.drawable.yourimage);

Intent intent = new Intent(this, YourImageViewerActivity.class);
Bundle bundle = new Bundle();
bundle.putString("data", yourImageUri);
intent.putExtras(bundle);
startActivity(intent);
onCreate() method:
Bundle bundle = getIntent().getExtras();
String yourImageUri= bundle.getString("data");
Bitmap bitmap = BitmapFactory.decodeFile(yourImageUri);
ImageView myImageView = (ImageView)findViewById(R.id.imageView1);
myImageView.setImageBitmap(bitmap);

If you are trying to add an image to you layout from the XML file then
<ImageView
android:id="#+id/imageView1"
android:src="#drawable/book" <- Change this to your drawable item
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1" />

Related

ImageView size is changed when changing the image

I have the problem that I have a layout with an ImageView. With AsyncTask I load an image from the web. It is a panorama picture. If I start up the Fragment, the image I load with src="#drawable/pano" is shown perfectly. It has full height and I can scroll through the panorama.
As soon as the new image is loaded into the ImageView the imageview rescales so that the height is:
Before the AsyncTask (Image is loaded from drawables...):
And this is after the AsyncTask loaded the image:
Here is my xml file:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
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=".MainActivity" >
<HorizontalScrollView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_centerInParent="true"
android:overScrollMode="never"
android:scrollbars="none" >
<RelativeLayout
android:layout_width="wrap_content"
android:layout_height="match_parent" >
<ImageView
android:id="#+id/img1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentTop="true"
android:adjustViewBounds="true"
android:scaleType="fitCenter"
android:src="#drawable/pano" />
</RelativeLayout>
</HorizontalScrollView>
AsyncTask Code:
public class DownloadPanorama extends
AsyncTask<ImageView, Void, Bitmap> {
ImageView imageView;
Bitmap bm;
public DownloadPanorama(ImageView mChart) {
imageView = mChart;
}
#Override
protected Bitmap doInBackground(ImageView... imageViews) {
return download_Image((String) imageView.getTag());
}
#Override
protected void onPostExecute(Bitmap result) {
imageView.setImageBitmap(result);
}
private Bitmap download_Image(String url) {
Bitmap bm = null;
try {
URL aURL = new URL(url);
URLConnection conn = aURL.openConnection();
conn.connect();
InputStream is = conn.getInputStream();
BufferedInputStream bis = new BufferedInputStream(is);
bm = BitmapFactory.decodeStream(bis);
bis.close();
is.close();
return bm;
}
}
Also happens when not using AsyncTask and only using raw setImageBitmap... So I don't know if I have to change the scaleType in my xml file or if I need to set it again after loading a new image?
I would try changing:
android:layout_height="wrap_content"
to
android:layout_height="fill_parent"
in your ImageView.
If that doesn't work, you might be able to scale your bitmap:
myBitmap = Bitmap.createScaledBitmap(myBitmap, width, height,true);
EDIT
It sounds like from your comments and updated question that you know the size you would like the image to be (1200x400). You have two things you can do to get this size. The first, and recommended, is to replace the line
bm = BitmapFactory.decodeStream(bis);
with
BitmapFactory.Options options = new BitmapFactory.Options();
options.outWidth=1200;
options.outHeight=400;
bm = BitmapFactory.decodeStream(bis, new Rect(0,0,0,0), options);
The other option is to change your View bounds. In your comments above, it sounds like the bounds might change, so you would have to repeat this each time you loaded a new image of different size:
RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) imageView.getLayoutParams();
params.width = 1200;
params.height = 400;
imageView.setLayoutParams(params);
You need to change
android:adjustViewBounds="true"
to
android:adjustViewBounds="false"

Make a drawable in Android created programmatically fits parent's width and has proportional height

So I am loading images from URLs with this method
public Drawable loadImage(String url) {
try {
InputStream is = (InputStream) new URL(url).getContent();
Drawable d = Drawable.createFromStream(is, "src name");
return d;
} catch (Exception e) {
System.out.println(e.getMessage()+" oh noo ");
return null;
}
}
But I want the image's width to be the same as its parent (that is the root element with height and width 100%). I couldn't find a way to do it using only XML. It always leaves paddings on the edges. And I found out it is because the image doesn't have the same ratio of the screen. screen is, for example 16:9 and image is 4:3. Android will make paddings to fill this difference.
Do you know how can I do it programmatically when I load the image? And I need this image to remain as big as the screen's width even when the device rotates (so I think I will need to calculate it gain)
I am using this code to get the size of the screen
public Size getScreenSize(){
Size screenSize = new Size();
DisplayMetrics metrics = new DisplayMetrics();
this.activity.getWindowManager().getDefaultDisplay().getMetrics(metrics);
screenSize.height = metrics.heightPixels;
screenSize.width = metrics.widthPixels;
return screenSize;
}
public class Size{
public double height;
public double width;
}
#EDIT1
This is how I insert the drawable in the View. The view is already declared in the activity's XML
ImageView picture = (ImageView) findViewById(R.id.picture);
picture.setImageDrawable(loadImage(url));
#EDIT2
this is how I wrote the activity layout and its style
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity" >
<!-- style="#style/globalHeader" -->
<LinearLayout
style="#style/globalHeader"
>
<TextView
android:id="#+id/name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#fff"
android:textSize="18sp"
android:textStyle="bold"
/>
<TextView
android:id="#+id/subtitle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#fff"
android:textSize="14sp"
/>
</LinearLayout>
<ImageView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/picture"
android:adjustViewBounds="true"
android:scaleType="centerCrop"
android:background="#f00"
>
</ImageView>
<TextView
android:id="#+id/desc"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="20dp"
/>
<TextView
android:id="#+id/details"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
/>
</LinearLayout>
This is the appearance I want to achieve
https://docs.google.com/a/uniriotec.br/file/d/0B2abPynX9PhkODhRVEkwcUphY28/edit?pli=1
I think so this is the one you are finding for.
just rescale the image of drawable taken from internet.
Bitmap bit = BitmapFactory.decodeResource(getApplicationContext()
.getResources(), drawable);
if (bit != null) {
Bitmap resizedBitmap = Bitmap.createScaledBitmap(bit, width,
height, true);
imageView.setBitmap(resizedBitmap);
}
the width and height are calculated below
DisplayMetrics disp = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(disp);
int width = disp.widthPixels;
int height = disp.heightPixels;
#EDIT
private Bitmap loadImage(String URL)
{
Bitmap bitmap = null;
InputStream in = null;
try {
in = OpenHttpConnection(URL);
bitmap = BitmapFactory.decodeStream(in);
in.close();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
return bitmap;
}
private InputStream OpenHttpConnection(String urlString)
throws IOException
{
InputStream in = null;
int response = -1;
URL url = new URL(urlString);
URLConnection conn = url.openConnection();
if (!(conn instanceof HttpURLConnection))
throw new IOException("Not an HTTP connection");
try{
HttpURLConnection httpConn = (HttpURLConnection) conn;
httpConn.setAllowUserInteraction(false);
httpConn.setInstanceFollowRedirects(true);
httpConn.setRequestMethod("GET");
httpConn.connect();
response = httpConn.getResponseCode();
if (response == HttpURLConnection.HTTP_OK)
{
in = httpConn.getInputStream();
}
}
catch (Exception ex)
{
throw new IOException("Error connecting");
}
return in;
}
Directly take the bitmap image and rescale it and use it.
Not sure how will it behave with device rotation, but I believe you actually can do it from your xml layout, setting your ImageView.ScaleType to CENTER_CROP should do the trick.-
CENTER_CROP : Scale the image uniformly (maintain the image's aspect ratio) so that both dimensions (width and height) of the image will be equal to or larger than the corresponding dimension of the view (minus padding).
<ImageView
android:id="#+id/picture"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:scaleType="centerCrop" />
Try this
<ImageView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:adjustViewBounds="true"
android:id="#+id/picture"
android:scaleType="fitXY"
android:background="#f00"
>

Cant get ImageView onItemClick from custom ListView Android [EDIT]

I've implemented a custom ListView, this is the structure of each row:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal" >
<ImageView
android:id="#+id/imagenEvento"
android:layout_width="80dp"
android:layout_height="80dp"
android:scaleType="centerCrop"
android:adjustViewBounds="false"
android:paddingBottom="2dp"
android:contentDescription="#string/contenidoImagen"
/>
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:gravity="left"
android:padding="10dp"
android:orientation="vertical" >
<TextView
android:id="#+id/titulo"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="17sp"
android:textAppearance="?android:attr/textAppearanceLarge" />
<TextView
android:id="#+id/sitio"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="12sp"
android:textAppearance="?android:attr/textAppearanceSmall" />
<TextView
android:id="#+id/fecha"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="12sp"
android:textAppearance="?android:attr/textAppearanceSmall" />
</LinearLayout>
I've setted to my ListView and adapter and it works fine while accesing data, but when i try to convert an ImageView to a byteArray so i can send it to another Activitie, i can't get the ImageView
lv = (ListView) findViewById(R.id.lista);
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> a, View v, int position, long id) {
//creo el nuevo objeto para poder llamarlo
Intent intent = new Intent(AllProductsActivity.this, PostActivity.class);
//Creo la informacion para pasar entre actividades
Bundle informacion= new Bundle();
informacion.putInt("id", eventos.get(position).getID());
Bitmap bmp = BitmapFactory.decodeResource(a.getResources(), R.id.imagenEvento);
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bmp.compress(Bitmap.CompressFormat.PNG, 100, stream);
byte[] byteArray = stream.toByteArray();
informacion.putByteArray("imagen", byteArray);
}
});
I'm getting my bmp NULL:
Bitmap bmp = BitmapFactory.decodeResource(a.getResources(), R.id.imagenEvento);
I guess i should indicate the position of the item due it's in a ListView but i don't know how to do it
[EDIT]
The problem is solved, i'm getting the image in the next Activity, but, i'm getting always the top image from the ListView of this Activity, how can i get the clicked Image?
Instead of:
Bitmap bmp = BitmapFactory.decodeResource(a.getResources(), R.id.imagenEvento);
to get your bitmap image. Try this:
ImageView image = (ImageView)v.findViewByID(R.id.iamgeenEvento);
Bitmap bmp = ((BitmapDrawable)image.getDrawable()).getBitmap();
Your original code was trying to decode the imageview itself as a bitmap and as it's not a bitmap would return a null value.
The ImageView that your using is just a reference so no need to convert it into an array just pass the reference directly as static Or make a static class that holds such references so that you can use it later, But also you can save the image of the imageview as bitmap and encode save that image as byte array and decode it when needed, and later use it imageView as imageView.setImageBitmap(bitmap);
imageView.buildDrawingCache();
Bitmap bmap = imageView.getDrawingCache();
public String BitmapToString(Bitmap bitmap){
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG,100,baos);
byte[] b = baos.toByteArray();
String image = Base64.encodeToString(b, Base64.DEFAULT);
return image;
}
public Bitmap StringToBitmap(String image){
byte[] encodeByte = Base64.decode(image, Base64.DEFAULT);
Bitmap bitmap = BitmapFactory.decodeByteArray(encodeByte, 0 , encodeByte.length);
return bitmap;
}

How to load thumbnail from custom directory?

I have searched a lot but I got samples to fetch thumbnail from an Url or from Http,
but I actually need to get thumbnail of an image from my own directory on sdcard withot accesing the Android default thumbnail directory, thats is I need to fetch a thumbnail of an image from
mnt/sdcard/myown/1.png
Can anybody help for this please?
Thanks in advance.
Environment.getExternalStorageDirectory() returns "/mnt/sdcard"
String imagePath = Environment.getExternalStorageDirectory().toString() + PATH_TO_IMAGE;
Bitmap bitmap = BitmapFactory.decodeFile(imagePath);
#Override
public void onCreate(Bundle savedInstanceState) {
button1 = (Button) findViewById(R.id.button1);
button1.setOnClickListener(onClickListener);
image = (ImageView) findViewById(R.id.imageView1);
}
private OnClickListener onClickListener = new OnClickListener() {
#Override
public void onClick(final View v) {
switch(v.getId()){
case R.id.button1:
String imagePath = Environment.getExternalStorageDirectory().toString() +"/myown/1.png";
Bitmap bitmap = BitmapFactory.decodeFile(imagePath);
image.setImageBitmap(bitmap);
break;
}
}
};
your layout.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<ImageView
android:id="#+id/imageView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/android" />
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Change Image" />
</LinearLayout>

Android Progress bar on ImageView

I am developing an app in which user will take Picture from camera and display it on preview screen having image view.
**CameraCapture.java**
class ButtonClickHandler implements View.OnClickListener
{
public void onClick( View view ){
myVib.vibrate(50);
startCameraActivity();
}
}
protected void startCameraActivity()
{
File filenew = new File( _path );
Uri outputFileUri = Uri.fromFile( filenew );
Intent intent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE );
intent.putExtra( MediaStore.EXTRA_OUTPUT, outputFileUri );
intent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
startActivityForResult( intent, 0 );
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
switch( resultCode )
{
case 0:
break;
case -1:
//pictaken++;
onPhotoTaken();
break;
}
}
protected void onPhotoTaken()
{
//pictaken=true;
Intent i = new Intent(CameraCapture.this,Preview.class);
startActivity(i);
}
In my Preview class the captured picture is displayed on ImageView
**Preview.java**
File imgFile = new File("/sdcard/DCIM/Camera/test.jpg");
if(imgFile.exists()){
// Bitmap myBitmap = BitmapFactory.decodeFile(imgFile.getAbsolutePath());
ImageView myImage = (ImageView) findViewById(R.id.image);
Bitmap myBitmap = BitmapFactory.decodeFile(imgFile.getAbsolutePath());
Matrix mat = new Matrix();
String degree="90";
mat.postRotate(Integer.parseInt(degree));
Bitmap bMapRotate = Bitmap.createBitmap(myBitmap, 0, 0,myBitmap.getWidth(),myBitmap.getHeight(), mat, true);
myImage.setImageBitmap(bMapRotate);
//myImage.setImageBitmap(myBitmap);
}
_image = ( ImageView ) findViewById( R.id.image );
Is there is any way to show progress bar on the ImageView till it load the Captured image from SD card.
Thnx in advance :)
Put your ImageView and Progressbar in a RelativeLayout. For your ProgressBar, use:
android:layout_centerInParent="true"
Which will center it in the RelativeLayout, meaning over the ImageView. You might also want to hide the ProgressBar when the image has loaded:
progressBar.setVisibility(View.Gone)
when the image has been loaded.
Sample code:
<RelativeLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:adjustViewBounds="true"/>
<ProgressBar
style="?android:attr/progressBarStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:visibility="visible"/>
</RelativeLayout>
This is my solution. It is a little bit different. You can use it to create intro view with an image and progress bar. Here, progress bar is at 150dp to the bottom of center. FrameLayout can also be used.
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
<ImageView
android:id="#+id/imageView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:contentDescription="#string/intro_description"
android:scaleType="fitXY"
android:src="#drawable/intro" />
<ProgressBar
android:id="#+id/progress"
style="?android:attr/progressBarStyle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_marginTop="150dp"
android:visibility="visible" />
</FrameLayout>

Categories

Resources