- Java 双重比较
- java - 比较器与 Apache BeanComparator
- Objective-C 完成 block 导致额外的方法调用?
- database - RESTful URI 是否应该公开数据库主键?
我正在尝试编写一个小代码,允许我在从相机拍摄照片后直接发送,我的意思是当我从相机拍摄照片时,这张图片将直接发送到服务器而不存储在我的手机或 SD 卡中,所以我制作了这段代码,但我不知道它是否正确,因为实际上它向我显示了很多消息错误,但我不知道问题出在哪里,或者是否有人可以告诉我在哪里可以找到类似的代码,
// Upload Direct From Camera
camButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent_gallery = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
intent_gallery.putExtra( MediaStore.EXTRA_OUTPUT, SERVER_URL + "uploadFromCamera.php" );
startActivityForResult(intent_gallery, SELECT_IMAGE);
}
});
...
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK) {
if (requestCode == SELECT_IMAGE) {
Uri selectedImageUri = data.getData();
String selectedImagePath = getPath( selectedImageUri );
String url = SERVER_URL + "uploadFromCamera.php";
if ( selectedImagePath != null ) {
//Send to server
}
}
}
}
public String getPath(Uri uri) {
String result = null;
String[] projection = { MediaStore.Images.Media.DATA };
Cursor cursor = getContentResolver().query(uri, projection, null, null, null);
if(cursor.moveToFirst()){;
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
result = cursor.getString(column_index);
}
cursor.close();
return result;
}
最佳答案
此代码有助于将图像上传到 TomCat 服务器。
安卓应用
import java.io.ByteArrayOutputStream;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import android.support.v7.app.ActionBarActivity;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.provider.MediaStore;
import android.util.Base64;
import android.view.View;
import android.widget.ImageView;
import android.widget.Toast;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;
@SuppressLint("NewApi")
public class MainActivity extends Activity {
ProgressDialog prgDialog;
String encodedString;
RequestParams params = new RequestParams();
String imgPath, fileName;
Bitmap bitmap, lesimg;
private static int RESULT_LOAD_IMG = 1;
private static int REQUEST_IMAGE_CAPTURE = 1;
private static String TIME_STAMP="null";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
prgDialog = new ProgressDialog(this);
prgDialog.setCancelable(false);
}
public void loadImagefromGallery(View view) {
Intent galleryIntent = new Intent(Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(galleryIntent, RESULT_LOAD_IMG);
}
public void dispatchTakePictureIntent(View view) {
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
startActivityForResult(takePictureIntent, REQUEST_IMAGE_CAPTURE);
}
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == RESULT_OK) {
Bundle extras = data.getExtras();
Bitmap imageBitmap = (Bitmap) extras.get("data");
ImageView imgView = (ImageView) findViewById(R.id.imgView);
imgView.setImageBitmap(imageBitmap);
lesimg=imageBitmap;
String currentDateTimeString = DateFormat.getDateTimeInstance().format(new Date());
String hjkl=currentDateTimeString.replaceAll(" ", "_");
String hiop=hjkl.replaceAll(":", "-");
TIME_STAMP=hiop;
fileName=TIME_STAMP+".jpeg";
params.put("filename", fileName);
}
}
public void uploadImage(View v) {
encodeImagetoString();
}
public void encodeImagetoString() {
new AsyncTask<Void, Void, String>() {
protected void onPreExecute() {
};
@Override
protected String doInBackground(Void... params) {
BitmapFactory.Options options = null;
options = new BitmapFactory.Options();
options.inSampleSize = 3;
bitmap=lesimg;
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 50, stream);
byte[] byte_arr = stream.toByteArray();
encodedString = Base64.encodeToString(byte_arr, 0);
return "";
}
@Override
protected void onPostExecute(String msg) {
prgDialog.setMessage("Calling Upload");
prgDialog.show();
params.put("image", encodedString);
triggerImageUpload();
}
}.execute(null, null, null);
}
public void triggerImageUpload() {
makeHTTPCall();
}
public void makeHTTPCall() {
prgDialog.setMessage("Invoking JSP");
prgDialog.show();
AsyncHttpClient client = new AsyncHttpClient();
client.post("http://Your Ip Address or Localhost:8080/ImageUploadWebApp/uploadimg.jsp",
params, new AsyncHttpResponseHandler() {
@Override
public void onSuccess(String response) {
prgDialog.hide();
Toast.makeText(getApplicationContext(), response,
Toast.LENGTH_LONG).show();
}
@Override
public void onFailure(int statusCode, Throwable error,
String content) {
prgDialog.hide();
if (statusCode == 404) {
Toast.makeText(getApplicationContext(),
"Requested resource not found",
Toast.LENGTH_LONG).show();
}
else if (statusCode == 500) {
Toast.makeText(getApplicationContext(),
"Something went wrong at server end",
Toast.LENGTH_LONG).show();
}
else {
Toast.makeText(
getApplicationContext(),
"Error Occured \n Most Common Error: \n1. Device not connected to Internet\n2. Web App is not deployed in App server\n3. App server is not running\n HTTP Status code : "
+ statusCode, Toast.LENGTH_LONG)
.show();
}
}
});
}
@Override
protected void onDestroy() {
super.onDestroy();
if (prgDialog != null) {
prgDialog.dismiss();
}
}
}
安卓 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/imgView"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_weight="1" >
</ImageView>
<Button
android:id="@+id/buttonLoadPicture"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_weight="0"
android:onClick="dispatchTakePictureIntent"
android:text="Click Picture" >
</Button>
<Button
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginTop="25dp"
android:onClick="uploadImage"
android:text="Upload" />
</LinearLayout>
服务器部分在 Eclipse 中创建动态 Web 项目并使用 TomCat 服务器运行它
网络应用
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import org.apache.commons.codec.binary.Base64;
public class ManipulateImage {
public static byte[] convertStringtoImage(String encodedImageStr, String fileName) {
byte[] imageByteArray = Base64.decodeBase64(encodedImageStr);
try {
// URL url = new URL("http://www.amrood.com/index.htm?language=en#j2se");
imageByteArray = Base64.decodeBase64(encodedImageStr);
// Write Image into File system - Make sure you update the path
FileOutputStream imageOutFile = new FileOutputStream("C:/Some file Path" + fileName);
imageOutFile.write(imageByteArray);
imageOutFile.close();
System.out.println("Image Successfully Stored");
} catch (FileNotFoundException fnfe) {
System.out.println("Image Path not found" + fnfe);
} catch (IOException ioe) {
System.out.println("Exception while converting the Image " + ioe);
}
return imageByteArray;
}
public static String[] display(){
File folder = new File("C:/Some file Path");
File[] listOfFiles = folder.listFiles();
String [] k = new String[listOfFiles.length];
Arrays.fill(k,"none");
for (int i = 0; i < listOfFiles.length; i++) {
if (listOfFiles[i].isFile()) {
System.out.println("File " + listOfFiles[i].getName());
k[i]="File " + listOfFiles[i].getName();
} else if (listOfFiles[i].isDirectory()) {
System.out.println("Directory " + listOfFiles[i].getName());
}
}
return k;
}
}
小服务程序
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.ResourceBundle;
import java.util.StringTokenizer;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class DisplayImageServlet extends javax.servlet.http.HttpServlet implements javax.servlet.Servlet {
static final long serialVersionUID = 1L;
String image_name = "";
ResourceBundle props = null;
String filePath = "";
private static final int BUFSIZE = 100;
private ServletContext servletContext;
public DisplayImageServlet() {
super();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println("FROM SERVLET");
sendImage(getServletContext(), request, response);
}
public void sendImage(ServletContext servletContext,
HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
this.servletContext = servletContext;
String reqUrl = request.getRequestURL().toString();
StringTokenizer tokens = new StringTokenizer(reqUrl, "/");
int noOfTokens = tokens.countTokens();
String tokensString[] = new String[noOfTokens];
int count = 0;
while (tokens.hasMoreElements()) {
tokensString[count++] = (String) tokens.nextToken();
}
String folderName = tokensString[noOfTokens - 2];
image_name = tokensString[noOfTokens - 1];
filePath = "/" + folderName + "/" + image_name;
String fullFilePath = "D:/AndroidStudioProjects" + filePath;
System.out.println("FULL PATH :: "+fullFilePath);
doDownload(fullFilePath, request, response);
}
private void doShowImageOnPage(String fullFilePath,
HttpServletRequest request, HttpServletResponse response)
throws IOException {
response.reset();
response.setHeader("Content-Disposition", "inline");
response.setHeader("Cache-Control", "no-cache");
response.setHeader("Expires", "0");
response.setContentType("image/tiff");
byte[] image = getImage(fullFilePath);
OutputStream outputStream = response.getOutputStream();
outputStream.write(image);
outputStream.close();
}
private void doDownload(String filePath, HttpServletRequest request,
HttpServletResponse response) throws IOException {
File fileName = new File(filePath);
int length = 0;
ServletOutputStream outputStream = response.getOutputStream();
ServletContext context = servletContext;
String mimetype = context.getMimeType(filePath);
response.setContentType((mimetype != null) ? mimetype
: "application/octet-stream");
response.setContentLength((int) fileName.length());
response.setHeader("Content-Disposition", "attachment; filename=\""
+ image_name + "\"");
byte[] bbuf = new byte[BUFSIZE];
DataInputStream in = new DataInputStream(new FileInputStream(fileName));
while ((in != null) && ((length = in.read(bbuf)) != -1)) {
outputStream.write(bbuf, 0, length);
}
in.close();
outputStream.flush();
outputStream.close();
}
private byte[] getImage(String filename) {
byte[] result = null;
String fileLocation = filename;
File f = new File(fileLocation);
result = new byte[(int)f.length()];
try {
FileInputStream in = new FileInputStream(fileLocation);
in.read(result);
}
catch(Exception ex) {
System.out.println("GET IMAGE PROBLEM :: "+ex);
ex.printStackTrace();
}
return result;
}
}
将这个 Jsp 放在 Web 内容中
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%
String imgEncodedStr = request.getParameter("image");
String fileName = request.getParameter("filename");
System.out.println("Filename: "+ fileName);
if(imgEncodedStr != null){
response.setIntHeader("Refresh", 1);
byte[] imageByteArray=( ManipulateImage.convertStringtoImage(imgEncodedStr, fileName));//edited
System.out.println("Inside if");
out.print("Image upload complete, Please check your directory");
} else{
System.out.println("Inside else");
out.print("Image is empty");
}
%>
您可以在给定的文件夹中看到上传的图片。
关于android - 从相机捕获图像并将其直接发送到服务器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20928101/
有人能给我一些代码示例,了解如何从相机捕获“完整”图像,然后在“startActivityForResult”中将其转换为字节,以及显示在 imageView 中的位图。任何帮助将不胜感激。 山姆 最
我有一个带有两个圆的组,当我用平移过渡移动其中一个时,我应该看到静止的一个保持在中心(位于场景图的中间),而另一个移动。取而代之的是,“摄像机”跟随移动的圆圈,使其看起来好像都在分开。 有没有一种方法
我希望停止 Phonegap 将图片保存到 iOS 上的相机胶卷。 我发现了一种可能的解决方案,但我不太喜欢它。该解决方案需要通过删除这行代码来 fork phonegap API。 UIImageW
我最近开始使用 JOGL,我知道如何在 Canvas 上创建和绘制对象,但我找不到有关如何设置和旋转相机的教程或说明。我只找到了源代码,但由于我对此很陌生,所以它没有太大帮助。 有人知道一个好的教程或
关闭。这个问题需要多问focused 。目前不接受答案。 想要改进此问题吗?更新问题,使其仅关注一个问题 editing this post . 已关闭 8 年前。 Improve this ques
我想实现这样的目标: 因此,您捕获和处理的唯一内容是矩形中的区域。我需要这个,因为我想做一些 OCR 而我不想要整个屏幕。 最佳答案 也许可以帮助您这个来源,(在相机预览顶部绘制一个边界框以捕获部分图
我正在开发一个 Android 应用程序,我希望我的应用程序能够拍照并显示它们。我的问题是它制作了图片,将它存储在 SD 卡上但没有在我的应用程序中显示它,ImageView 保持空白。这是我的代码:
我正在研究 Android 相机教程,SDK 11。出于某种原因,我在 handleCameraPhoto() 中得到了一个空指针。我唯一看到的是“无法将结果 ResultInfo{who=null,
我一直在尝试实现此代码,我在其中从相机捕获图像并将其显示在我的图像查看器中,然后可以将其设置为墙纸。它在我的模拟器中运行良好,但在我的手机上,当我拍摄图像并单击“确定”时,它会强制关闭。有什么帮助吗?
我想将预览中的某些像素更改为比其余像素暗一点。假设我希望预览的上半部分比预览的下半部分暗一点。 我试图像这样使用 setPreviewCallback: camera.setPreviewCallba
我想为我的应用程序启用相机/照片库设置。我可以显示警报以编程方式启用这些吗就像应用程序启动时一样。我已附上图片以显示我希望看到我的应用程序的类似设置 对于我的应用程序,我没有看到此设置。 我的问题是这
所以我正在开发类似于相机应用程序的东西。它在原生 OpenGL 纹理上绘制实时相机预览。如果按下按钮,则会以原始形式捕获静态图像(可能比实时预览分辨率更高)。 这是我的代码的大纲。为了清楚起见,我没有
我想在我的 Android 应用程序中启动相机 Activity ,我知道该怎么做。我想问一下当相机 Activity 结束时,我如何检查它是否是用户拍摄的照片或视频? 已更新 我有一个对话框,其中询
我在横向模式下有自定义全屏摄像头。设备尺寸为 1024 x 600。 支持的预览尺寸列表 宽 x 高 176 x 144 320 x 240 352 x 288 528 x 432 640 x 480
请看下图!! 所以在这张图片中...您可以看到底部的弹出窗口,当用户“点击”“相机”按钮时,它会为用户提供 3 个选项。 那是什么观点?它是一个模态视图 Controller ,在选择一个选项时被关闭
我发布了一个应用程序,其中一项基本功能是允许用户拍照,然后将该照片保存在其外部存储上的特定文件夹中。 一切似乎都运行良好,但我现在收到两份报告,声称在拍照后单击“完成”退出相机(并返回到 Activi
我在尝试实时更换相机时遇到问题,它适用于本地视频,但远程人员看不到新相机,但仍然可以看到旧相机。我试图停止流并再次初始化,但仍然无法正常工作。这只是我的一些代码。 我到处搜索,但找不到解决方案。有人可
一个简单但非常复杂的问题:为 Flutter 相机添加点击对焦功能的最佳方法是什么? 我在整个万维网上搜索了优雅的解决方案,但一无所获。 你有想法吗? 最佳答案 我可能会迟到,但你可以试试 adv_c
我正在尝试使用 gluLookAt 方法设置 3D 相机。所以我有一个 10x10x10 的立方体,现在我想在那个立方体内移动相机。我有这样的事情: gluLookAt( camera->x,came
我赠送一个 UIImagePickerController在我的应用程序中通过在 sheet 中呈现逻辑修饰符。简而言之,以下三种类型处理显示和关闭 UIImagePickerController 的
我是一名优秀的程序员,十分优秀!