Uploads the image from the specified {@code url} via {@code MediaService}.

@return the {@code mediaId} of the uploaded image.
766424
private static long uploadImage(MediaServiceInterface mediaService, String url)
      throws IOException {
    // Create image.
    Image image = new Image();
    image.setType(MediaMediaType.IMAGE);
    image.setData(com.google.api.ads.common.lib.utils.Media.getMediaDataFromUrl(url));

    // Upload image.
    Image uploadedImage = (Image) mediaService.upload(new Media[] {image})[0];
    return uploadedImage.getMediaId();
  }
1335242
public static String read(URL url) throws IOException, NotFoundException {
        BufferedImage image = ImageIO.read(url);
        return read(image);
    }
1024587
public static UploadimgResult mediaUploadimg(String access_token,URI uri){
		HttpPost httpPost = new HttpPost(BASE_URI+"/cgi-bin/media/uploadimg");
		CloseableHttpClient tempHttpClient = HttpClients.createDefault();
		try {
			HttpEntity entity = tempHttpClient.execute(RequestBuilder.get().setUri(uri).build()).getEntity();
			HttpEntity reqEntity = MultipartEntityBuilder.create()
					 .addBinaryBody("media",EntityUtils.toByteArray(entity),ContentType.get(entity),UUID.randomUUID().toString()+".jpg")
			         .addTextBody(PARAM_ACCESS_TOKEN, API.accessToken(access_token))
			         .build();
			httpPost.setEntity(reqEntity);
			return LocalHttpClient.executeJsonResult(httpPost,UploadimgResult.class);
		} catch (Exception e) {
			logger.error("", e);
		} finally{
			try {
				tempHttpClient.close();
			} catch (Exception e) {
				logger.error("", e);
			}
		}
		return null;
	}
364719
public static Image getInstance(byte imgb[]) throws BadElementException,
			MalformedURLException, IOException {
		InputStream is = null;
		try {
			is = new java.io.ByteArrayInputStream(imgb);
			int c1 = is.read();
			int c2 = is.read();
			int c3 = is.read();
			int c4 = is.read();
			is.close();

			is = null;
			if (c1 == 'G' && c2 == 'I' && c3 == 'F') {
				GifImage gif = new GifImage(imgb);
				return gif.getImage(1);
			}
			if (c1 == 0xFF && c2 == 0xD8) {
				return new Jpeg(imgb);
			}
			if (c1 == 0x00 && c2 == 0x00 && c3 == 0x00 && c4 == 0x0c) {
				return new Jpeg2000(imgb);
			}
			if (c1 == 0xff && c2 == 0x4f && c3 == 0xff && c4 == 0x51) {
				return new Jpeg2000(imgb);
			}
			if (c1 == PngImage.PNGID[0] && c2 == PngImage.PNGID[1]
					&& c3 == PngImage.PNGID[2] && c4 == PngImage.PNGID[3]) {
				return PngImage.getImage(imgb);
			}
			if (c1 == 0xD7 && c2 == 0xCD) {
				return new ImgWMF(imgb);
			}
			if (c1 == 'B' && c2 == 'M') {
				return BmpImage.getImage(imgb);
			}
			if ((c1 == 'M' && c2 == 'M' && c3 == 0 && c4 == 42)
					|| (c1 == 'I' && c2 == 'I' && c3 == 42 && c4 == 0)) {
				RandomAccessFileOrArray ra = null;
				try {
					ra = new RandomAccessFileOrArray(imgb);
					Image img = TiffImage.getTiffImage(ra, 1);
                    if (img.getOriginalData() == null)
                        img.setOriginalData(imgb);
					return img;
				} finally {
					if (ra != null)
						ra.close();
				}

			}
			if ( c1 == 0x97 && c2 == 'J' && c3 == 'B' && c4 == '2' ) {
				is = new java.io.ByteArrayInputStream(imgb);
				is.skip(4);
				int c5 = is.read();
				int c6 = is.read();
				int c7 = is.read();
				int c8 = is.read();
				if ( c5 == '\r' && c6 == '\n' && c7 == 0x1a && c8 == '\n' ) {
					int file_header_flags = is.read();
					@SuppressWarnings("unused")
					int number_of_pages = -1;
					if ( (file_header_flags & 0x2) == 0x2 ) {
						number_of_pages = (is.read() << 24) | (is.read() << 16) | (is.read() << 8) | is.read();
					}
					is.close();
					// a jbig2 file with a file header.  the header is the only way we know here.                                                           
					// embedded jbig2s don't have a header, have to create them by explicit use of Jbig2Image?
					// nkerr, 2008-12-05  see also the getInstance(URL)
					RandomAccessFileOrArray ra = null;
					try {
						ra = new RandomAccessFileOrArray(imgb);
						Image img = JBIG2Image.getJbig2Image(ra, 1);
						if (img.getOriginalData() == null)
							img.setOriginalData(imgb);
						return img;
					} finally {
						if (ra != null)
							ra.close();
					}
				}
			}
			throw new IOException(
					"The byte array is not a recognized imageformat.");
		} finally {
			if (is != null) {
				is.close();
			}
		}
	}
357703
public JSONObject sendImageRequest(String url, byte[] image, HashMap<String, Object> options) {
        AipRequest request = new AipRequest();
        preOperation(request);
        String content = Base64Util.encode(image);
        request.addBody("image", content);
        if (options != null) {
            request.addBody(options);
        }
        request.setUri(url);
        request.addHeader(Headers.CONTENT_ENCODING,
                HttpCharacterEncoding.ENCODE_UTF8);
        request.addHeader(Headers.CONTENT_TYPE, HttpContentType.JSON_DATA);
        request.setBodyFormat(EBodyFormat.RAW_JSON);
        postOperation(request);
        return requestServer(request);
    }
51772
public MediaItem getMediaItem(String id) {
		
		DailyMotionUrl url = new DailyMotionUrl(requestPrefix + id);
		
		HttpRequest request;
		try {
			request = requestFactory.buildGetRequest(url);
			DailyMotionVideo video = request.execute().parseAs(DailyMotionVideo.class);
			
			if(video != null) {
				MediaItem mediaItem = new DailyMotionMediaItem(video);
				return mediaItem;
			}
			
		} catch (Exception e) {
			
		}

		return null;
	}
159285
@Nullable public de.uniulm.omi.cloudiator.flexiant.client.domain.Image getImage(
        final String imageUUID) throws FlexiantException {
        final io.github.cloudiator.flexiant.extility.Image image =
            this.getResource(imageUUID, ResourceType.IMAGE,
                io.github.cloudiator.flexiant.extility.Image.class);
        if (image == null) {
            return null;
        }
        return new de.uniulm.omi.cloudiator.flexiant.client.domain.Image(image);
    }
23691
public UploadFile getUploadFile(HttpServletRequest request, String id) {
    UploadFile uploadFile = null;
    Debug.logVerbose("[JdonFramework]--> getUploadFile session filter id=" + id, module);
    try {
      uploadFile = getUploadFileFromSession(request, id);
      if (uploadFile == null) {
        uploadFile = imageFilter.getUploadFile(request, id);
      }
    } catch (Exception ex) {
      Debug.logWarning(" getUploadFile error" + ex, module);

    }
    return uploadFile;
  }
875356
public URL getImageUrl(BaseType baseType, String id) throws FanartTvException {
        StringBuilder url = getBaseUrl(baseType);

        // Add the ID
        url.append(id);

        // Add the API Key
        url.append(DELIMITER_APIKEY).append(apiKey);

        // Add the client API Key
        if (StringUtils.isNotBlank(clientKey)) {
            url.append(DELIMITER_CLIENT_KEY).append(clientKey);
        }

        return convertUrl(url);
    }
1193733
@SuppressWarnings({ "null", "unused" })
  @NotNull
  Media processRequest(@NotNull final MediaRequest mediaRequest) {

    // detect media source
    MediaSource mediaSource = null;
    List<Class<? extends MediaSource>> mediaSources = mediaHandlerConfig.getSources();
    if (mediaSources == null || mediaSources.isEmpty()) {
      throw new RuntimeException("No media sources defined.");
    }
    MediaSource firstMediaSource = null;
    for (Class<? extends MediaSource> candidateMediaSourceClass : mediaSources) {
      MediaSource candidateMediaSource = AdaptTo.notNull(adaptable, candidateMediaSourceClass);
      if (candidateMediaSource.accepts(mediaRequest)) {
        mediaSource = candidateMediaSource;
        break;
      }
      else if (firstMediaSource == null) {
        firstMediaSource = candidateMediaSource;
      }
    }
    // if no media source was detected use first media resource defined
    if (mediaSource == null) {
      mediaSource = firstMediaSource;
    }
    Media media = new Media(mediaSource, mediaRequest);

    // resolve media format names to media formats
    MediaFormatResolver mediaFormatResolver = new MediaFormatResolver(mediaFormatHandler);
    if (!mediaFormatResolver.resolve(mediaRequest.getMediaArgs())) {
      media.setMediaInvalidReason(MediaInvalidReason.INVALID_MEDIA_FORMAT);
      return media;
    }

    // if only downloads are accepted prepare media format filter set which only contains download media formats
    if (!resolveDownloadMediaFormats(mediaRequest.getMediaArgs())) {
      media.setMediaInvalidReason(MediaInvalidReason.INVALID_MEDIA_FORMAT);
      return media;
    }

    // apply defaults to media args
    if (mediaRequest.getMediaArgs().isIncludeAssetWebRenditions() == null) {
      mediaRequest.getMediaArgs().includeAssetWebRenditions(mediaHandlerConfig.includeAssetWebRenditionsByDefault());
    }

    // preprocess media request before resolving
    List<Class<? extends MediaProcessor>> mediaPreProcessors = mediaHandlerConfig.getPreProcessors();
    if (mediaPreProcessors != null) {
      for (Class<? extends MediaProcessor> processorClass : mediaPreProcessors) {
        MediaProcessor processor = AdaptTo.notNull(adaptable, processorClass);
        media = processor.process(media);
        if (media == null) {
          throw new RuntimeException("MediaPreProcessor '" + processor + "' returned null, request: " + mediaRequest);
        }
      }
    }

    // resolve media request
    media = mediaSource.resolveMedia(media);
    if (media == null) {
      throw new RuntimeException("MediaType '" + mediaSource + "' returned null, request: " + mediaRequest);
    }

    // generate markup (if markup builder is available) - first accepting wins
    List<Class<? extends MediaMarkupBuilder>> mediaMarkupBuilders = mediaHandlerConfig.getMarkupBuilders();
    if (mediaMarkupBuilders != null) {
      for (Class<? extends MediaMarkupBuilder> mediaMarkupBuilderClass : mediaMarkupBuilders) {
        MediaMarkupBuilder mediaMarkupBuilder = AdaptTo.notNull(adaptable, mediaMarkupBuilderClass);
        if (mediaMarkupBuilder.accepts(media)) {
          media.setElement(mediaMarkupBuilder.build(media));
          break;
        }
      }
    }

    // postprocess media request after resolving
    List<Class<? extends MediaProcessor>> mediaPostProcessors = mediaHandlerConfig.getPostProcessors();
    if (mediaPostProcessors != null) {
      for (Class<? extends MediaProcessor> processorClass : mediaPostProcessors) {
        MediaProcessor processor = AdaptTo.notNull(adaptable, processorClass);
        media = processor.process(media);
        if (media == null) {
          throw new RuntimeException("MediaPostProcessor '" + processor + "' returned null, request: " + mediaRequest);
        }
      }
    }

    return media;
  }
123910
public static void getTo(
                    final URL from_url,
                    final OutputStream to_stream,
                    final List<MediaType> accept_media_types
                    )
    {
        _LOG_.debug( "HTTP GET: from URL=" + from_url + ", accept=" + accept_media_types );

        AcceptHeaderRequestCallback  callback =
                        new AcceptHeaderRequestCallback( accept_media_types );
        OutputStreamResponseExtractor  extractor = new OutputStreamResponseExtractor( to_stream );
        _execute( from_url, HttpMethod.GET, callback, extractor );
    }
1265782
public Material addImage(InputStream inputStream, String fileName) {
        return upload(MediaType.image, inputStream, fileName);
    }
77727
public BufferedImage downloadImage() throws Exception {
		BufferedImage image = null;
		// try to recognize the type of the image from the url so that the correct format and file extension
		// are used when saving the thumbnail image or the original image.
		// In case that the url does not contain a known image extension, the jpg extension is used.
		String[] splitted = imageUrl.split("\\.");
		String fileExtension = (splitted[splitted.length - 1]).toLowerCase();
		if (!fileExtension.equals("jpg") && !fileExtension.equals("jpeg") && !fileExtension.equals("png")
				&& !fileExtension.equals("bmp") && !fileExtension.equals("gif")) {
			fileExtension = "jpg";
		}
		// this name filename will be used for the saved image file
		String imageFilename = downloadFolder + imageId + "." + fileExtension;

		// initialize the url, checking that it is valid
		URL url = null;
		try {
			url = new URL(imageUrl);
		} catch (MalformedURLException e) {
			System.out.println("Malformed url exception. Url: " + imageUrl);
			throw e;
		}

		HttpURLConnection conn = null;
		FileOutputStream fos = null;
		ReadableByteChannel rbc = null;
		InputStream in = null;
		boolean success = false;
		try {
			conn = (HttpURLConnection) url.openConnection();
			conn.setInstanceFollowRedirects(followRedirects);
			conn.setConnectTimeout(connectionTimeout); // TO DO: add retries when connections times out
			conn.setReadTimeout(readTimeout);
			conn.connect();
			success = true;
		} catch (Exception e) {
			System.out.println("Connection related exception at url: " + imageUrl);
			throw e;
		} finally {
			if (!success) {
				conn.disconnect();
			}
		}

		success = false;
		try {
			in = conn.getInputStream();
			success = true;
		} catch (Exception e) {
			System.out.println("Exception when getting the input stream from the connection at url: "
					+ imageUrl);
			throw e;
		} finally {
			if (!success) {
				in.close();
			}
		}

		rbc = Channels.newChannel(in);

		// if an Exception is thrown in the following code, the file that was created must be deleted
		try {
			// just copy the file
			fos = new FileOutputStream(imageFilename);
			fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE);
			fos.close();
			in.close();
			rbc.close();
			conn.disconnect();
			try { // first try reading with the default class
				image = ImageIO.read(new File(imageFilename));
			} catch (IllegalArgumentException e) {
				// this exception is probably thrown because of a greyscale jpeg image
				System.out.println("Exception: " + e.getMessage() + " | Image: " + imageFilename + " URL: "
						+ imageUrl);
				image = ImageIOGreyScale.read(new File(imageFilename)); // retry with the modified class
			}
		} catch (Exception e) { // in case of any other exception delete the image and re-throw the exception
			System.out.println("Exception: " + e.toString() + " | Image: " + imageFilename + " URL: "
					+ imageUrl);
			throw (e);
		} finally {
			if (image == null) { // if the image could not be read into a BufferedImage object then delete it
				File imageFile = new File(imageFilename);
				imageFile.delete();
				System.out.println("Deleting image with id " + imageId + ", url: " + imageUrl);
				throw new Exception("Could not read into BufferedImage");
			} else {
				if (saveThumb) { // save a thumbnail of the original image
					ImageScaling scale = new ImageScaling(thumbnailSizeInPixels);
					BufferedImage scaledImage = scale.maxPixelsScaling(image);
					FileOutputStream out = new FileOutputStream(new File(imageFilename.replace("."
							+ fileExtension, "-thumb." + fileExtension)));
					ImageIO.write(scaledImage, fileExtension, out);
					out.close();
				}
				if (!saveOriginal) {// delete the original image if needed
					File imageFile = new File(imageFilename);
					imageFile.delete();
				}
			}
			// close the open streams
			fos.close();
			in.close();
			rbc.close();
			conn.disconnect();
		}
		return image;
	}
16568
private HttpResponse directUpload(GenericUrl initiationRequestUrl) throws IOException {
    updateStateAndNotifyListener(UploadState.MEDIA_IN_PROGRESS);

    HttpContent content = mediaContent;
    if (metadata != null) {
      content = new MultipartContent().setContentParts(Arrays.asList(metadata, mediaContent));
      initiationRequestUrl.put("uploadType", "multipart");
    } else {
      initiationRequestUrl.put("uploadType", "media");
    }
    HttpRequest request =
        requestFactory.buildRequest(initiationRequestMethod, initiationRequestUrl, content);
    request.getHeaders().putAll(initiationHeaders);
    // We do not have to do anything special here if media content length is unspecified because
    // direct media upload works even when the media content length == -1.
    HttpResponse response = executeCurrentRequest(request);
    boolean responseProcessed = false;
    try {
      if (isMediaLengthKnown()) {
        totalBytesServerReceived = getMediaContentLength();
      }
      updateStateAndNotifyListener(UploadState.MEDIA_COMPLETE);
      responseProcessed = true;
    } finally {
      if (!responseProcessed) {
        response.disconnect();
      }
    }
    return response;
  }
1136428
public DownloadResult downloadFile(String mediaId)
            throws APIConnectionException, APIRequestException {
        Preconditions.checkArgument(null != mediaId, "mediaId is necessary");

        ResponseWrapper response = _httpClient.sendGet(_baseUrl + resourcePath + "?mediaId=" + mediaId);
        return DownloadResult.fromResponse(response, DownloadResult.class);
    }
1202339
public String postByRead(
                    final String url,
                    final InputStream input,
                    final String media_type
                    )
    {
        InputStreamRequestCallback  callback =
                        new InputStreamRequestCallback( input, MediaType.valueOf( media_type ) );
        String  location = _execute( url, HttpMethod.POST,
                        callback,
                        new LocationHeaderResponseExtractor() );

        return location;
    }
522588
public GetMediaInfoOfFileResponse getMediaInfoOfFile(GetMediaInfoOfFileRequest request) {
        checkNotNull(request, "The parameter request should NOT be null.");
        checkStringNotEmpty(request.getBucket(), "The parameter bucket should NOT be null or empty string.");
        checkStringNotEmpty(request.getKey(), "The parameter key should NOT be null or empty string.");
        InternalRequest internalRequest = createRequest(HttpMethodName.GET, request, MEDIAINFO);
        internalRequest.addParameter("bucket", request.getBucket());
        internalRequest.addParameter("key", request.getKey());
        return invokeHttpClient(internalRequest, GetMediaInfoOfFileResponse.class);
    }