Editorial Workflows

Upload image to WordPress V2

public workflow

Install Workflow...

This workflow contains at least one Python script. Only use it if you trust the person who shared this with you, and if you know exactly what it does.

I understand, install the workflow!

This is a workflow for Editorial, a Markdown and plain text editor for iOS. To download it, you need to view this page on a device that has the app installed.

Description: Upload image to Wordpress Media Library and the ability to select size of predefined image sizes from Wordpress and the position of the image. An img link with all information of size, width, alignment and alt text is added at the cursor position. Works with Wordpress Retina plugins.
Read more at http://www.jackenhack.com/editorial-app-workflow-upload-image-wordpress-media-library/

Shared by: Jacken Zimmermann

Comments: Comment Feed (RSS)

Jacken — 31 Jan 2015
A newer version with lots of improvements here: http://www.editorial-workflows.com/workflow/6357181481877504/sSCTFSH_QcI

+ Add Comment

Workflow Preview
Set SiteURL ?
Variable Name
SiteURL
Value
http://www.jackenhack.com/xmlrpc.php
Set Wordpress Username ?
Variable Name
username
Value
username here
Set Wordpress Password ?
Variable Name
password
Value
password here.
Check modules Installed ?
Source Code
#coding: utf-8
import workflow
import os, sys

#sys.path += [os.path.join(os.getcwd(), 'pypi-modules')]
sys.path += [os.path.join(os.getcwd(), '../../../Documents/pypi-modules')]
import imp
try:
    imp.find_module('wordpress_xmlrpc')
    workflow.set_output('True')
except ImportError:
    workflow.set_output('False')
if missing module... ?
Run the block if
Input
  • is Equal to
  • is Not Equal to
  • Contains
  • Doesn't Contain
  • Matches Regular Expression
True
Missing module alert ?
Title
Missing Module
Message
You need to install the wordpress_xmlrpc module first.
Button 1
Instructions
Output Value
instruction
Button 2
(don't show)
Output Value
Button 3
(don't show)
Output Value
Show Cancel Button
ON
…End If
If instruction button pressed, go to instructions ?
Run the block if
Input
  • is Equal to
  • is Not Equal to
  • Contains
  • Doesn't Contain
  • Matches Regular Expression
instruction
Open URL ?
Open in
  • In-App Browser
  • Default App / Safari
URL
http://www.jackenhack.com/editorial-app-import-modules-with-pipista/
Tab
  • Last-used Tab
  • New Tab
  • Tab with ID:
Unique identifier
Wait until Loaded
OFF
Reveal Browser Automatically
ON
Stop ?
Stop
  • This Workflow
  • Repeat Block
Show HUD Alert
OFF
Message
Stopped
…End If
Python scale and upload to WP ?
Source Code
#coding: utf-8
import workflow
#import ui

import sys, os, photos, console, clipboard, Image
#sys.path += [os.path.join(os.getcwd(), '../Commands/pypi-modules')]
sys.path += [os.path.join(os.getcwd(), '../../../Documents/pypi-modules')]
from wordpress_xmlrpc import Client, WordPressPost
from wordpress_xmlrpc.compat import xmlrpc_client
from wordpress_xmlrpc.methods import media, posts
from cStringIO import StringIO
from PIL import Image
import pickle

prefsfile = 'prefs.pkl'
DEFAULTWIDTH = 600
imagequality = 85

def readprefs(filename):
	if os.path.isfile(filename):
		input = open(filename, 'r')
		width = pickle.load(input)
		input.close()
	else:
		width = DEFAULTWIDTH
	return width
	
def writeprefs(filename, width):
	output = open(filename, 'wb')
	# Pickle dictionary using protocol 0.
	pickle.dump(width, output)
	output.close()

def scaleimage(img, newwidth):
	if img.size[0] < newwidth:
		# dont upscale small image
		console.alert('Image size', 'Image is smaller than ' + str(newwidth) + ' px wide.', 'OK')
		return img
	wpercent = (newwidth/float(img.size[0]))
	hsize = int((float(img.size[1])*float(wpercent)))
	img = img.resize((newwidth,hsize), Image.ANTIALIAS)
	return img

username = workflow.get_variable('username')
site = workflow.get_variable('SiteURL')
password = workflow.get_variable('password')
if not username:
	console.alert('Missing Username', 'Set the username in the script variable of this workflow.')
	workflow.stop()
if not site:
	console.alert('Missing SiteURL', 'Set the site URL to the xmlpc.php in the script variable of this Workflow')
	workflow.stop()

if not password:
	console.alert('Missing password', 'Set the password in the script variable of this Workflow')
	workflow.stop()

prefs = {}
console.clear()
# Try to log in to Wordpress site

try:
	client = Client(site, username, password)
except Exception as e:
	console.hud_alert('Problem logging in', 'error',4)
	workflow.stop()
selphoto = photos.pick_image(show_albums=True)
if not selphoto:
	console.hud_alert('No photo selected!', 'error', 2)
	workflow.stop()
width = readprefs(prefsfile)
shouldresize = console.alert('Image Size' + str(selphoto.size[0]) + 'x' + str(selphoto.size[1]) + '.', 'Do you want to resize?', 'Original', 'Resize')
if shouldresize == 2:
	newwidth = console.input_alert('Current image width ' + str(selphoto.size[0]) + ', resize to', '', str(width), 'Scale')
	newwidth = int(newwidth)
	if newwidth != width:
		# User changed the width, save for next time in preference file
		width = newwidth
		writeprefs(prefsfile, width)

# Ask for file name
filename = console.input_alert('filename', '', '', 'Save')
if not filename:
	print 'No filename given.'
	workflow.stop()
# check for file extension, add if missing
if filename[-4:] != '.jpg':
	filename = filename + '.jpg'
if shouldresize == 'Resize':
	selphoto = scaleimage(selphoto, int(width))
imgfile = StringIO()
selphoto.save(imgfile, format='JPEG', quality = imagequality)
imagestring = imgfile.getvalue()

# prepare metadata
data = {
        'name': filename,
        'type': 'image/jpg',  # mimetype
}

console.show_activity()

# read the binary file and let the XMLRPC library encode it into base64
data['bits'] = xmlrpc_client.Binary(imagestring)

try:
	response = client.call(media.UploadFile(data))
except Exception as e:
	console.hud_alert('Problem uploading', 'error', 3)
	workflow.stop()

# response == {
#       'id': 6,
#       'file': 'picture.jpg'
#       'url': 'http://www.example.com/wp-content/uploads/2012/04/16/picture.jpg',
#       'type': 'image/jpg',
# }
attachment_id = response['id']

s = []
result = client.call(media.GetMediaItem(attachment_id))
link = result.link
head, tail = os.path.split(link)
for x in result.metadata['sizes']:
 	img = result.metadata['sizes'][x]['file']
 	w = str(result.metadata['sizes'][x]['width'])
	h = str(result.metadata['sizes'][x]['height'])
	
 	url = head + '/' + img
	imagesize = url + '|' + w + '|' + h + '|' + str(attachment_id) + '|' + x
	s.append(tail + ' - ' + x + ' ' + w + 'x' + h + '	' + imagesize)
	output = '\n'.join(s) 		
workflow.set_output(output)
console.hide_activity()
select image size ?
Title
Select image size
List (Lines)
Input
Multiple Selection
OFF
Show in Popover
OFF
save image size ?
Variable Name
imagesize
Value
Input
select image alignment ?
Title
select image alignment
List (Lines)
Left alignleft Center aligncenter Right alignright
Multiple Selection
OFF
Show in Popover
OFF
save image alignmet ?
Variable Name
alignment
Value
Input
Ask for image alt text ?
Title
Enter the image Alt text
Initial Text
  • Single Line
  • Multiple Lines
Keyboard Options:
Set Variable ?
Variable Name
altText
Value
Input
URL and size ?
Source Code
#coding: utf-8
import workflow
import editor

# = workflow.get_input()
imagesize = workflow.get_variable('imagesize')
align = workflow.get_variable('alignment')
alttext = workflow.get_variable('altText')
url, x, y, imageid, imgsize = imagesize.split('|')

completeURL = '<img src="{src}" alt="{alt}" width="{x}" height="{y}" class="{alignment} size-{size} wp-image-{id}" />'.format(src=url, alt=alttext, x=str(x), y=str(y), alignment=align, size=imgsize, id=imageid)
workflow.set_output(completeURL)
Replace Selected Text ?
Replacement Text
Input