台灣最大程式設計社群網站
線上人數
1161
 
會員總數:243277
討論主題:188067
歡迎您免費加入會員
討論區列表 >> Android APP 開發 >> InputStream 讀取 imageview
[]  
[我要回覆]
回應主題 加入我的關注話題 檢舉此篇討論 將提問者加入個人黑名單
InputStream 讀取 imageview
價值 : 20 QP  點閱數:62 回應數:0

樓主

小焰
初學者
8 1
14 1
發送站內信





請問下面我用紅色字體的地方,要如何讓他可以讀取到imageview的圖片?

[/code]
package com.example.takming.ocr;

import android.Manifest;
import android.app.Activity;
import android.content.ContentValues;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.net.Uri;
import android.os.AsyncTask;
import android.provider.MediaStore;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.Toast;

import com.google.api.client.extensions.android.json.AndroidJsonFactory;
import com.google.api.client.http.javanet.NetHttpTransport;
import com.google.api.services.vision.v1.Vision;
import com.google.api.services.vision.v1.VisionRequestInitializer;
import com.google.api.services.vision.v1.model.AnnotateImageRequest;
import com.google.api.services.vision.v1.model.BatchAnnotateImagesRequest;
import com.google.api.services.vision.v1.model.BatchAnnotateImagesResponse;
import com.google.api.services.vision.v1.model.Feature;
import com.google.api.services.vision.v1.model.Image;
import com.google.api.services.vision.v1.model.TextAnnotation;

import org.apache.commons.io.IOUtils;

import java.io.IOException;
import java.io.InputStream;
import java.util.Arrays;

public class MainActivity extends AppCompatActivity {
Uri imgUri; //用來參照拍照存檔的 Uri 物件
ImageView imv; //用來參照 ImageView 物件
private Vision vision;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_NOSENSOR);//設定螢幕不隨手機旋轉
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);//設定螢幕直向顯示
imv = (ImageView)findViewById(R.id.imageView); //參照 Layout 中的 ImageView 元件



Vision.Builder visionBuilder = new Vision.Builder(new NetHttpTransport(), new AndroidJsonFactory(), null); //建立google cloud vision api

visionBuilder.setVisionRequestInitializer(
new VisionRequestInitializer("AIzaSyASDSDVcb3Y9812_rxYwapLYMQpu_eXjEM")); //google cloud vision api key

vision = visionBuilder.build();

textocr();

}

public void onGet(View v) {
if (ActivityCompat.checkSelfPermission(this, //檢查是否已取得寫入權限
Manifest.permission.WRITE_EXTERNAL_STORAGE) !=
PackageManager.PERMISSION_GRANTED) {
//尚未取得權限
ActivityCompat.requestPermissions(this, //向使用者要求允許寫入權限
new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
200);
}
else {
//已經取得權限
savePhoto(); //拍照並存檔
}
}

@Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
if (requestCode == 200){
if (grantResults[0] == PackageManager.PERMISSION_GRANTED){ //使用者允許權限
savePhoto(); //拍照並存檔
}
else { //使用者拒絕權限
Toast.makeText(this, "程式需要寫入權限才能運作", Toast.LENGTH_SHORT).show();
}
}
}

private void savePhoto () {
imgUri = getContentResolver().insert(
MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
new ContentValues());
Intent it = new Intent("android.media.action.IMAGE_CAPTURE");
it.putExtra(MediaStore.EXTRA_OUTPUT, imgUri); //將 uri 加到拍照 Intent 的額外資料中
startActivityForResult(it, 100);
}

public void onPick(View v) {
Intent it = new Intent(Intent.ACTION_GET_CONTENT); //動作設為 "選取內容"
it.setType("image/*"); //設定要選取的媒體類型為:所有類型的圖片
startActivityForResult(it, 101); //啟動意圖, 並要求傳回選取的圖檔
}

protected void onActivityResult (int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);

if(resultCode == Activity.RESULT_OK) { //要求的意圖成功了
switch(requestCode) {
case 100: //拍照
Intent it = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, imgUri);//設為系統共享媒體檔
sendBroadcast(it);
break;
case 101: //選取相片
imgUri = data.getData(); //取得選取相片的 Uri
break;
}
showImg(); //顯示 imgUri 所指明的相片
}
else {
Toast.makeText(this, requestCode==100? "沒有拍到照片":
"沒有選取相片", Toast.LENGTH_LONG)
.show();
}
}

void showImg() {
int iw, ih, vw, vh;
boolean needRotate; //用來儲存是否需要旋轉

BitmapFactory.Options option = new BitmapFactory.Options(); //建立選項物件
option.inJustDecodeBounds = true; //設定選項:只讀取圖檔資訊而不載入圖檔

//讀取圖檔資訊存入 Option 中
try {
BitmapFactory.decodeStream(getContentResolver().openInputStream(imgUri), null, option);
}
catch (IOException e) {
Toast.makeText(this, "讀取照片資訊時發生錯誤", Toast.LENGTH_LONG).show();
return;
}

iw = option.outWidth; //由 option 中讀出圖檔寬度
ih = option.outHeight; //由 option 中讀出圖檔高度
vw = imv.getWidth(); //取得 ImageView 的寬度
vh = imv.getHeight(); //取得 ImageView 的高度

int scaleFactor;
if(iw<ih) { //如果圖片的寬度小於高度
needRotate = false; //不需要旋轉
scaleFactor = Math.min(iw/vw, ih/vh); // 計算縮小比率
}
else {
needRotate = true; //需要旋轉
scaleFactor = Math.min(iw/vh, ih/vw); // 將 ImageView 的寬、高互換來計算縮小比率
}

option.inJustDecodeBounds = false; //關閉只載入圖檔資訊的選項
option.inSampleSize = scaleFactor; //設定縮小比例, 例如 2 則長寬都將縮小為原來的 1/2

//載入圖檔
Bitmap bmp = null;
try {
bmp = BitmapFactory.decodeStream(getContentResolver().openInputStream(imgUri), null, option);
} catch (IOException e) {
Toast.makeText(this, "無法取得照片", Toast.LENGTH_LONG).show();
}

if(needRotate) { //如果需要旋轉
Matrix matrix = new Matrix(); //建立 Matrix 物件
matrix.postRotate(90); //設定旋轉角度
bmp = Bitmap.createBitmap(bmp , //用原來的 Bitmap 產生一個新的 Bitmap
0, 0, bmp.getWidth(), bmp.getHeight(), matrix, true);
}

imv.setImageBitmap(bmp); //顯示圖片
}

private void textocr() {
AsyncTask.execute(new Runnable() {
@Override
public void run() {
try {
InputStream inputStream = getFileStreamPath();

byte[] photoData = IOUtils.toByteArray(inputStream);

Image inputImage = new Image();
inputImage.encodeContent(photoData);

Feature desiredFeature = new Feature(); //發出OCR請求
desiredFeature.setType("TEXT_DETECTION"); //TEXT_DETECTION為辨識少量文字api

AnnotateImageRequest request = new AnnotateImageRequest();
request.setImage(inputImage);
request.setFeatures(Arrays.asList(desiredFeature));

BatchAnnotateImagesRequest batchRequest = new BatchAnnotateImagesRequest();
batchRequest.setRequests(Arrays.asList(request));

BatchAnnotateImagesResponse batchResponse =
vision.images().annotate(batchRequest).execute();

final TextAnnotation text = batchResponse.getResponses()
.get(0).getFullTextAnnotation();

runOnUiThread(new Runnable() {
@Override
public void run() {
Toast.makeText(getApplicationContext(),
text.getText(), Toast.LENGTH_LONG).show();
}
});

} catch(Exception e) {
Log.d("ERROR", e.getMessage());
}
}
});
}
}
[code]

搜尋相關Tags的文章: [ InputStream 讀取 imageview ] ,
本篇文章發表於2018-10-08 00:24
別忘捐VP感謝幫助你的人 新手會員瞧一瞧
目前尚無任何回覆
   

回覆
如要回應,請先登入.