从相机or相册获取图片并显示

本文介绍了一个简单的Android应用程序,该程序实现了从相机拍照和从相册选择图片的功能,并展示了如何处理这些图片以便在应用中展示。

啊这个技术应该算是十分稀松平常了,但是对于小白来说,还是要费一番功夫的。因此在这里贴上我的代码,也是为了以后用到的时候方便找。。。


package com.example.photo;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;



import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;

public class MainActivity extends Activity {

	Button camera, gallery;
	ImageView photo;
	private static int CAMERA_REQUEST_CODE = 1;
	private static int GALLERY_REQUEST_CODE = 2;
	private static int SCALE=5;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		camera=(Button)findViewById(R.id.camera);
		gallery=(Button)findViewById(R.id.gallery);
		photo=(ImageView)findViewById(R.id.photo);
		camera.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				Intent openCameraIntent = new Intent(
						MediaStore.ACTION_IMAGE_CAPTURE);
				
				//这里如果不加入访问SD卡权限会报错
				// <uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS" >
				// <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
				
				Uri imageUri = Uri.fromFile(new File(Environment
						.getExternalStorageDirectory(), "test.png"));
				// 指定照片保存路径(SD卡),test.png为一个临时文件,每次拍照后这个图片都会被替换
				openCameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
				startActivityForResult(openCameraIntent, CAMERA_REQUEST_CODE);
			}
		});

		gallery.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
				intent.setType("image/*");
				Uri imageUri = Uri.fromFile(new File(Environment
						.getExternalStorageDirectory(), "test.png"));
				// 指定照片保存路径(SD卡),test.png为一个临时文件,每次拍照后这个图片都会被替换
				intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
				startActivityForResult(intent, GALLERY_REQUEST_CODE);

			}
		});
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		//另外,使用保存文件之后再读取而不是直接用data的原因是,这里返回的data是一个缩略图,十分不清晰
		
		if (requestCode == CAMERA_REQUEST_CODE) {// 将保存在本地的图片取出并缩小后显示在界面上
			Bitmap bitmap = BitmapFactory.decodeFile(Environment
					.getExternalStorageDirectory()
					+ "/test.png");
			Bitmap newBitmap = ImageTools.zoomBitmap(bitmap, bitmap.getWidth()
					/ SCALE, bitmap.getHeight() / SCALE);
			// 由于Bitmap内存占用较大,这里需要回收内存,否则会报out of memory异常
			bitmap.recycle();
			// 将处理过的图片显示在界面上,并保存到本地
			ImageView imageView = (ImageView) findViewById(R.id.photo);
			imageView.setImageBitmap(newBitmap);

		} else if (requestCode == GALLERY_REQUEST_CODE) {
			if (data == null)
				return;
			else {
				Uri uri;
				uri = data.getData();
				try {
					Bitmap bm = MediaStore.Images.Media.getBitmap(
							this.getContentResolver(), uri);
					ImageView imageView = (ImageView) findViewById(R.id.photo);
					imageView.setImageBitmap(bm);
				} catch (FileNotFoundException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}
	}

}


### 如何使用 Vue.js 创建情人节 3D 相册 #### 使用的技术栈 为了构建一个功能齐全的情人节3D相册,主要依赖以下几种技术: - **Vue.js**:作为前端框架,提供了一种声明式的编程风格来创建用户界面。其组件化的结构非常适合用来管理复杂的UI逻辑。 - **Three.js**:这是一个用于渲染三维图形的强大库,在浏览器中利用WebGL工作。它能够帮助快速搭建起具有交互性的3D场景[^2]。 #### 准备环境 确保已经安装了Node.js和npm工具之后,可以通过命令行初始化一个新的Vue项目添加必要的依赖项: ```bash vue create valentine-album cd valentine-album npm install three @types/three --save ``` #### 构建基本布局 在`src/App.vue`文件内定义好页面的基础架构以及引入所需的外部资源(如样式表),同时设置好容器元素供后续加载3D模型之用。 ```html <template> <div id="app"> <header class="album-header">Valentine's Day Album</header> <section ref="sceneContainer"></section> </div> </template> <script lang="ts"> import { defineComponent, onMounted } from 'vue'; // Import Three.js components and utilities here... export default defineComponent({ name: 'App', setup() { let scene; const initScene = () => { // Initialize the Three.js scene... }; onMounted(() => { initScene(); }); return {}; }, }); </script> <style scoped> .album-header { text-align: center; } /* Add more styles as needed */ </style> ``` #### 初始化 Three.js 场景 接下来就是编写具体的业务逻辑——即如何配置相机、光源、物体等要素构成完整的3D空间,将其绑定到之前准备好的DOM节点上显示出来。这部分内容通常放在`initScene()`函数内部完成。 ```javascript const initScene = () => { // Create a new instance of Scene object. scene = new THREE.Scene(); // Set up camera parameters (field of view, aspect ratio, near clipping plane, far clipping plane). const fov = 75; // Field Of View angle in degrees. const aspectRatio = window.innerWidth / window.innerHeight; const nearPlane = 0.1; const farPlane = 1000; // Instantiate PerspectiveCamera with these settings. const camera = new THREE.PerspectiveCamera( fov, aspectRatio, nearPlane, farPlane); // Position our virtual "camera". camera.position.z = 5; // Define renderer properties including size matching viewport dimensions. const renderer = new THREE.WebGLRenderer({ antialias: true }); renderer.setSize(window.innerWidth, window.innerHeight); // Append canvas element to DOM container specified by reference attribute. document.querySelector('#app section').appendChild(renderer.domElement); animate(); // Start animation loop. function animate() { requestAnimationFrame(animate); // Schedule next frame update. // Rotate objects or apply other transformations over time. /* Example transformation code goes here */ // Render current state into WebGL context attached to page. renderer.render(scene, camera); } }; ``` #### 添加照片集成为3D对象 为了让相册具备立体感,可以考虑把每一张图片都转换成独立的Mesh实例放置在一个环形阵列当中围绕中心旋转展示给观众看。这里需要用到TextureLoader去异步获取图像数据流再映射至几何体表面形成最终可见的效果。 ```javascript async function loadImagesIntoScene(imageUrls) { imageUrls.forEach((url, index) => { const textureLoader = new THREE.TextureLoader(); textureLoader.load(url, (texture) => { const geometry = new THREE.PlaneGeometry(1, 1); const material = new THREE.MeshBasicMaterial({ map: texture }); const mesh = new THREE.Mesh(geometry, material); mesh.rotation.y = ((Math.PI * 2) / imageUrls.length) * index; mesh.position.x = Math.cos(mesh.rotation.y) * 4; mesh.position.y = Math.sin(mesh.rotation.y) * 4; scene.add(mesh); }); }); } onMounted(async () => { await initScene(); const urls = [ '/path/to/photo1.jpg', '/path/to/photo2.png' // More photo paths can be added here... ]; loadImagesIntoScene(urls); }); ``` 以上便是基于Vue.js与Three.js组合实现的一个简易版情人节主题3D电子相册的大致流程概述。
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值