从App Engine将图像数据发送到Android应用程序

栏目: 后端 · 发布时间: 5年前

内容简介:翻译自:https://stackoverflow.com/questions/35230940/send-image-data-to-android-app-from-app-engine

在我的App Engine后端,我有一种方法可以从Google云端存储中获取图像

@ApiMethod(
        name = "getProfileImage",
        path = "image",
        httpMethod = ApiMethod.HttpMethod.GET)
public Image getProfileImage(@Named("imageName")String imageName){
    try{
        HttpTransport httpTransport = GoogleNetHttpTransport.newTrustedTransport();
        GoogleCredential credential = GoogleCredential.getApplicationDefault();

        Storage.Builder storageBuilder = new Storage.Builder(httpTransport,new JacksonFactory(),credential);
        Storage storage = storageBuilder.build();

        Storage.Objects.Get getObject = storage.objects().get("mybucket", imageName);

        ByteArrayOutputStream out = new ByteArrayOutputStream();
        // If you're not in AppEngine, download the whole thing in one request, if possible.
        getObject.getMediaHttpDownloader().setDirectDownloadEnabled(false);
        getObject.executeMediaAndDownloadTo(out);

        byte[] oldImageData = out.toByteArray();
        out.close();

        ImagesService imagesService = ImagesServiceFactory.getImagesService();

        return ImagesServiceFactory.makeImage(oldImageData);
    }catch(Exception e){
        logger.info("Error getting image named "+imageName);
    }
    return null;
}

我遇到的问题是当我在Android应用程序中调用图像数据时如何获取图像数据?

由于你无法从app引擎返回原语,我将其转换为Image,以便我可以在我的应用程序中调用getImageData()来获取byte [].

但是,返回到应用程序的Image对象与app引擎中的Image对象不同,因此没有getImageData().

如何将图像数据导入我的Android应用程序?

如果我创建一个其中包含byte []变量的Object,那么我将byte []变量设置为字符串数据并从该方法返回该对象将起作用吗?

更新

图像从Android应用程序发送. (此代码可能正确也可能不正确,我还没有调试过)

@WorkerThread
    public String startResumableSession(){
        try{
            File file = new File(mFilePath);
            long fileSize = file.length();
            file = null;
            String sUrl = "https://www.googleapis.com/upload/storage/v1/b/lsimages/o?uploadType=resumable&name="+mImgName;
            URL url = new URL(sUrl);
            HttpURLConnection urlConnection = (HttpURLConnection)url.openConnection();
            urlConnection.setRequestProperty("Authorization","");
            urlConnection.setRequestProperty("X-Upload-Content-Type","image/png");
            urlConnection.setRequestProperty("X-Upload-Content-Length",String.valueOf(fileSize));
            urlConnection.setRequestMethod("POST");

            if(urlConnection.getResponseCode() == HttpURLConnection.HTTP_OK){
                return urlConnection.getHeaderField("Location");
            }
        }catch(Exception e){
            e.printStackTrace();
        }
        return null;
    }

    private long sendNextChunk(String sUrl,File file,long skip){
        int bytesRead, bytesAvailable, bufferSize;
        byte[] buffer;
        int maxBufferSize = 524287;
        long totalBytesSent = 0;
        try{
            long fileSize = file.length();
            FileInputStream fileInputStream = new FileInputStream(file);
            skip = fileInputStream.skip(skip);

            bytesAvailable = fileInputStream.available();
            bufferSize = Math.min(bytesAvailable, maxBufferSize);
            totalBytesSent = skip + bufferSize;
            buffer = new byte[bufferSize];

            bytesRead = fileInputStream.read(buffer, 0, bufferSize);
            try {
                while (bytesRead > 0) {

                    try {
                        URL url = new URL(sUrl);
                        HttpURLConnection urlConnection = (HttpURLConnection)url.openConnection();
                        urlConnection.setDoInput(true);
                        urlConnection.setDoOutput(true);
                        urlConnection.setUseCaches(false);
                        urlConnection.setChunkedStreamingMode(524287);
                        urlConnection.setRequestMethod("POST");
                        urlConnection.setRequestProperty("Connection", "Keep-Alive");
                        urlConnection.setRequestProperty("Content-Type","image/png");
                        urlConnection.setRequestProperty("Content-Length",String.valueOf(bytesRead));
                        urlConnection.setRequestProperty("Content-Range", "bytes "+String.valueOf(skip)+"-"+String.valueOf(totalBytesSent)+"/"+String.valueOf(fileSize));

                        DataOutputStream outputStream = new DataOutputStream(urlConnection.getOutputStream());
                        outputStream.write(buffer, 0, bufferSize);

                        int code = urlConnection.getResponseCode();

                        if(code == 308){
                            String range = urlConnection.getHeaderField("Range");
                            return Integer.parseInt(range.split("-")[1]);
                        }else if(code == HttpURLConnection.HTTP_CREATED){
                            return -1;
                        }

                        outputStream.flush();
                        outputStream.close();
                        outputStream = null;
                    } catch (OutOfMemoryError e) {
                        e.printStackTrace();
//                        response = "outofmemoryerror";
//                        return response;
                        return -1;
                    }
                    fileInputStream.close();
                }
            } catch (Exception e) {
                e.printStackTrace();
//                response = "error";
//                return response;
                return -1;
            }
        }catch(Exception e){
            e.printStackTrace();
        }
        return -1;
    }

编辑2:

显然,人们不清楚我在我的Android应用程序中使用端点

我最终做了什么/发现你需要在带端点的api调用上调用execute()并返回从API传回的实际数据

api调用返回Image

public Image getProfileImage(@Named("id") long id, @Named("imageName")String imageName){
        try{
            ProfileRecord pr = get(id);
            HttpTransport httpTransport = GoogleNetHttpTransport.newTrustedTransport();
            GoogleCredential credential = GoogleCredential.getApplicationDefault();

            Storage.Builder storageBuilder = new Storage.Builder(httpTransport,new JacksonFactory(),credential);
            Storage storage = storageBuilder.build();

            Storage.Objects.Get getObject = storage.objects().get("mybucket", imageName);

        ByteArrayOutputStream out = new ByteArrayOutputStream();
        // If you're not in AppEngine, download the whole thing in one request, if possible.
        getObject.getMediaHttpDownloader().setDirectDownloadEnabled(false);
        getObject.executeMediaAndDownloadTo(out);

        byte[] oldImageData = out.toByteArray();
        out.close();
        return ImagesServiceFactory.makeImage(oldImageData);
    }catch(Exception e){
        logger.info("Error getting image named "+imageName);
    }
    return null;
}

然后在客户端我会这样称呼它来获得它

Image i = pr.profileImage(id,"name.jpg").execute();
byte[] data = i.decodeImageData();

翻译自:https://stackoverflow.com/questions/35230940/send-image-data-to-android-app-from-app-engine


以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,也希望大家多多支持 码农网

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

P2P网贷投资手册

P2P网贷投资手册

徐红伟 / 同济大学出版社 / 2015-4 / CNY 28.00

《P2P网贷投资手册》由“P2P网络借贷知多少”、“新手如何开始P2P网贷投资”和“如何确定适合自己的网贷投资策略”三部分组成。将网贷之家平台上众多投资人和从业者的智慧集结成册,分享给网贷投资上的同路人。一起来看看 《P2P网贷投资手册》 这本书的介绍吧!

在线进制转换器
在线进制转换器

各进制数互转换器

图片转BASE64编码
图片转BASE64编码

在线图片转Base64编码工具

URL 编码/解码
URL 编码/解码

URL 编码/解码