2011年3月28日星期一

儲存位圖檔案

Android OS 為每個應用程序保留獨立的文件結構.

例如:
com.AndroidBtmap 應用程序包的文件位於:
/data/data/com.AndroidBtmap/files/

修改上文"從 drawable 文件夾中加載位圖"程序, 把位圖檔案以 JPG 格式儲存於 /data/data/com.AndroidBtmap/files/ 中.

儲存位圖檔案
儲存位圖檔案

main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/hello"
/>
<ImageView
android:id="@+id/myimage"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
/>
<TextView
android:id="@+id/myimagewidth"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
/>
<TextView
android:id="@+id/myimageheight"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
/>
<Button
android:id="@+id/save"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Save"
/>
</LinearLayout>


package com.AndroidBtmap;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Bitmap.CompressFormat;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

public class AndroidBtmap extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);

ImageView myImage = (ImageView)findViewById(R.id.myimage);
TextView myImageWidth = (TextView)findViewById(R.id.myimagewidth);
TextView myImageHeight = (TextView)findViewById(R.id.myimageheight);
Button buttonSave = (Button)findViewById(R.id.save);

final Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.androidbiancheng);
int bitmapWidth = bitmap.getWidth();
int bitmapHeight = bitmap.getHeight();

myImage.setImageBitmap(bitmap);
myImageWidth.setText("Width: " + String.valueOf(bitmapWidth));
myImageHeight.setText("Height: " + String.valueOf(bitmapHeight));

buttonSave.setOnClickListener(new Button.OnClickListener(){

@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
FileOutputStream fos;
try {
fos = openFileOutput("MyBitmap.jpg", MODE_WORLD_READABLE);
bitmap.compress(CompressFormat.JPEG, 80, fos);
fos.flush();
fos.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

}});
}
}


2 則留言: